text stringlengths 81 112k |
|---|
Perform the derivation of master_secret into a key_block of req_len
requested length. See RFC 5246, section 6.3.
def derive_key_block(self, master_secret, server_random,
client_random, req_len):
"""
Perform the derivation of master_secret into a key_block of req_len
... |
Return verify_data based on handshake messages, connection end,
master secret, and read_or_write position. See RFC 5246, section 7.4.9.
Every TLS 1.2 cipher suite has a verify_data of length 12. Note also:
"This PRF with the SHA-256 hash function is used for all cipher
suites defined i... |
Postprocess cipher key for EXPORT ciphersuite, i.e. weakens it.
An export key generation example is given in section 6.3.1 of RFC 2246.
See also page 86 of EKR's book.
def postprocess_key_for_export(self, key, client_random, server_random,
con_end, read_or_write, req_... |
Generate IV for EXPORT ciphersuite, i.e. weakens it.
An export IV generation example is given in section 6.3.1 of RFC 2246.
See also page 86 of EKR's book.
def generate_iv_for_export(self, client_random, server_random,
con_end, read_or_write, req_len):
"""
... |
Parse /etc/protocols and return values as a dictionary.
def load_protocols(filename, _integer_base=10):
""""Parse /etc/protocols and return values as a dictionary."""
spaces = re.compile(b"[ \t]+|\n")
dct = DADict(_name=filename)
try:
with open(filename, "rb") as fdesc:
for line in ... |
Load manuf file from Wireshark.
param:
- filename: the file to load the manuf file from
def load_manuf(filename):
"""Load manuf file from Wireshark.
param:
- filename: the file to load the manuf file from"""
manufdb = ManufDA(_name=filename)
with open(filename, "rb") as fdesc:
for... |
Find OUI name matching to a MAC
def lookup(self, mac):
"""Find OUI name matching to a MAC"""
oui = ":".join(mac.split(":")[:3]).upper()
return self[oui] |
Find all MACs registered to a OUI
params:
- name: the OUI name
- case_sensitive: default to False
returns: a dict of mac:tuples (Name, Extended Name)
def reverse_lookup(self, name, case_sensitive=False):
"""Find all MACs registered to a OUI
params:
- name: the... |
In CCP, the payload of a DTO packet is dependent on the cmd field
of a corresponding CRO packet. Two packets correspond, if there
ctr field is equal. If answers detect the corresponding CRO, it will
interpret the payload of a DTO with the correct class. In CCP, there is
no other way, to ... |
Read the version from ``git describe``. It returns the latest tag with an
optional suffix if the current directory is not exactly on the tag.
Example::
$ git describe --always
v2.3.2-346-g164a52c075c8
The tag prefix (``v``) and the git commit sha1 (``-g164a52c075c8``) are
removed if p... |
We need to select the correct one on dissection. We use the length for
that, as 1 for client version would emply an empty list.
def _TLS_Ext_CertTypeDispatcher(m, *args, **kargs):
"""
We need to select the correct one on dissection. We use the length for
that, as 1 for client version would emply an emp... |
Reproduced from packet.py
def _show_or_dump(self, dump=False, indent=3,
lvl="", label_lvl="", first_call=True):
""" Reproduced from packet.py """
ct = AnsiColorTheme() if dump else conf.color_theme
s = "%s%s %s %s \n" % (label_lvl, ct.punct("###["),
... |
We try to compute a length, usually from a msglen parsed earlier.
If this length is 0, we consider 'selection_present' (from RFC 5246)
to be False. This means that there should not be any length field.
However, with TLS 1.3, zero lengths are always explicit.
def getfield(self, pkt, s):
... |
There is a hack with the _ExtensionsField.i2len. It works only because
we expect _ExtensionsField.i2m to return a string of the same size (if
not of the same value) upon successive calls (e.g. through i2len here,
then i2m when directly building the _ExtensionsField).
XXX A proper way to... |
Internal function used to generate the Records from
their template.
def _GenNetflowRecordV9(cls, lengths_list):
"""Internal function used to generate the Records from
their template.
"""
_fields_desc = []
for j, k in lengths_list:
_f_data = NetflowV9TemplateFieldDecoders.get(k, None)
... |
Used internally to process a single packet during defragmenting
def _netflowv9_defragment_packet(pkt, definitions, definitions_opts, ignored):
"""Used internally to process a single packet during defragmenting"""
# Dataflowset definitions
if NetflowFlowsetV9 in pkt:
current = pkt
while Netf... |
Process all NetflowV9/10 Packets to match IDs of the DataFlowsets
with the Headers
params:
- plist: the list of mixed NetflowV9/10 packets.
- verb: verbose print (0/1)
def netflowv9_defragment(plist, verb=1):
"""Process all NetflowV9/10 Packets to match IDs of the DataFlowsets
with the Heade... |
Convert DER octet string to PEM format (with optional header)
def der2pem(der_string, obj="UNKNOWN"):
"""Convert DER octet string to PEM format (with optional header)"""
# Encode a byte string in PEM format. Header advertizes <obj> type.
pem_string = ("-----BEGIN %s-----\n" % obj).encode()
base64_strin... |
Convert PEM string to DER format
def pem2der(pem_string):
"""Convert PEM string to DER format"""
# Encode all lines between the first '-----\n' and the 2nd-to-last '-----'.
pem_string = pem_string.replace(b"\r", b"")
first_idx = pem_string.find(b"-----\n") + 6
if pem_string.find(b"-----BEGIN", firs... |
Split PEM objects. Useful to process concatenated certificates.
def split_pem(s):
"""
Split PEM objects. Useful to process concatenated certificates.
"""
pem_strings = []
while s != b"":
start_idx = s.find(b"-----BEGIN")
if start_idx == -1:
break
end_idx = s.find... |
Concatenate all the certificates (PEM format for the export) in
'anchor_list' and write the result to file 'filename'. On success
'filename' is returned, None otherwise.
If you are used to OpenSSL tools, this function builds a CAfile
that can be used for certificate and CRL check.
def _create_ca_file(... |
Verifies either a Cert or an X509_Cert.
def verifyCert(self, cert):
""" Verifies either a Cert or an X509_Cert. """
tbsCert = cert.tbsCertificate
sigAlg = tbsCert.signature
h = hash_by_oid[sigAlg.algorithm.val]
sigVal = raw(cert.signatureValue)
return self.verify(raw(tbs... |
Note that this will always copy the signature field from the
tbsCertificate into the signatureAlgorithm field of the result,
regardless of the coherence between its contents (which might
indicate ecdsa-with-SHA512) and the result (e.g. RSA signing MD2).
There is a small inheritance tric... |
Return True if the certificate is self-signed:
- issuer and subject are the same
- the signature of the certificate is valid.
def isSelfSigned(self):
"""
Return True if the certificate is self-signed:
- issuer and subject are the same
- the signature of the certi... |
Given a list of trusted CRL (their signature has already been
verified with trusted anchors), this function returns True if
the certificate is marked as revoked by one of those CRL.
Note that if the Certificate was on hold in a previous CRL and
is now valid again in a new CRL and bot ar... |
Export certificate in 'fmt' format (DER or PEM) to file 'filename'
def export(self, filename, fmt="DER"):
"""
Export certificate in 'fmt' format (DER or PEM) to file 'filename'
"""
f = open(filename, "wb")
if fmt == "DER":
f.write(self.der)
elif fmt == "PEM":... |
Perform verification of certificate chains for that certificate.
A list of anchors is required. The certificates in the optional
untrusted list may be used as additional elements to the final chain.
On par with chain instantiation, only one chain constructed with the
untrusted candidates... |
Does the same job as .verifyChain() but using the list of anchors
from the cafile. As for .verifyChain(), a list of untrusted
certificates can be passed (as a file, this time).
def verifyChainFromCAFile(self, cafile, untrusted_file=None):
"""
Does the same job as .verifyChain() but usin... |
Does the same job as .verifyChainFromCAFile() but using the list
of anchors in capath directory. The directory should (only) contain
certificates files in PEM format. As for .verifyChainFromCAFile(),
a list of untrusted certificates can be passed as a file
(concatenation of the certifica... |
DEV: true if self is an answer from other
def answers(self, other):
"""DEV: true if self is an answer from other"""
if other.__class__ == self.__class__:
return (other.service + 0x40) == self.service or \
(self.service == 0x7f and
self.request_service_... |
Function used in the sending thread of sndrcv()
def _sndrcv_snd(pks, timeout, inter, verbose, tobesent, hsent, timessent, stopevent): # noqa: E501
"""Function used in the sending thread of sndrcv()"""
try:
i = 0
rec_time = timessent is not None
if verbose:
print("Begin emis... |
Function used to receive packets and check their hashret
def _sndrcv_rcv(pks, hsent, stopevent, nbrecv, notans, verbose, chainCC,
multi, _storage_policy=None):
"""Function used to receive packets and check their hashret"""
if not _storage_policy:
_storage_policy = lambda x, y: (x, y)
... |
Scapy raw function to send a packet and receive its answer.
WARNING: This is an internal function. Using sr/srp/sr1/srp is
more appropriate in many cases.
def sndrcv(pks, pkt, timeout=None, inter=0, verbose=None, chainCC=False,
retry=0, multi=False, rcv_pks=None, store_unanswered=True,
pr... |
Send packets at layer 3
send(packets, [inter=0], [loop=0], [count=None], [verbose=conf.verb], [realtime=None], [return_packets=False], # noqa: E501
[socket=None]) -> None
def send(x, inter=0, loop=0, count=None,
verbose=None, realtime=None,
return_packets=False, socket=None, *args, **kargs):
... |
Send packets at layer 2
sendp(packets, [inter=0], [loop=0], [iface=None], [iface_hint=None], [count=None], [verbose=conf.verb], # noqa: E501
[realtime=None], [return_packets=False], [socket=None]) -> None
def sendp(x, inter=0, loop=0, iface=None, iface_hint=None, count=None,
verbose=None, realtime=Non... |
Send packets at layer 2 using tcpreplay for performance
pps: packets per second
mpbs: MBits per second
realtime: use packet's timestamp, bending time with real-time value
loop: number of times to process the packet list
file_cache: cache packets in RAM instead of reading from disk at each iteration... |
Parse the output of tcpreplay and modify the results_dict to populate output information. # noqa: E501
Tested with tcpreplay v3.4.4
Tested with tcpreplay v4.1.2
:param stdout: stdout of tcpreplay subprocess call
:param stderr: stderr of tcpreplay subprocess call
:param argv: the command used in the... |
Send and receive packets at layer 3
def sr(x, promisc=None, filter=None, iface=None, nofilter=0, *args, **kargs):
"""Send and receive packets at layer 3"""
s = conf.L3socket(promisc=promisc, filter=filter,
iface=iface, nofilter=nofilter)
result = sndrcv(s, x, *args, **kargs)
s.clo... |
Send packets at layer 3 and return only the first answer
def sr1(x, promisc=None, filter=None, iface=None, nofilter=0, *args, **kargs):
"""Send packets at layer 3 and return only the first answer"""
s = conf.L3socket(promisc=promisc, filter=filter,
nofilter=nofilter, iface=iface)
ans,... |
Send and receive packets at layer 2
def srp(x, promisc=None, iface=None, iface_hint=None, filter=None,
nofilter=0, type=ETH_P_ALL, *args, **kargs):
"""Send and receive packets at layer 2"""
if iface is None and iface_hint is not None:
iface = conf.route.route(iface_hint)[0]
s = conf.L2socke... |
Send and receive packets at layer 2 and return only the first answer
def srp1(*args, **kargs):
"""Send and receive packets at layer 2 and return only the first answer"""
ans, _ = srp(*args, **kargs)
if len(ans) > 0:
return ans[0][1]
else:
return None |
Flood and receive packets at layer 3
prn: function applied to packets received
unique: only consider packets whose print
nofilter: put 1 to avoid use of BPF filters
filter: provide a BPF filter
iface: listen answers only on the given interface
def srflood(x, promisc=None, filter=None, iface=None, nofilter=... |
Flood and receive packets at layer 3 and return only the first answer
prn: function applied to packets received
verbose: set verbosity level
nofilter: put 1 to avoid use of BPF filters
filter: provide a BPF filter
iface: listen answers only on the given interface
def sr1flood(x, promisc=None, filter=None, i... |
Flood and receive packets at layer 2
prn: function applied to packets received
unique: only consider packets whose print
nofilter: put 1 to avoid use of BPF filters
filter: provide a BPF filter
iface: listen answers only on the given interface
def srpflood(x, promisc=None, filter=None, iface=None, iface_hi... |
Flood and receive packets at layer 2 and return only the first answer
prn: function applied to packets received
verbose: set verbosity level
nofilter: put 1 to avoid use of BPF filters
filter: provide a BPF filter
iface: listen answers only on the given interface
def srp1flood(x, promisc=None, filter=None, ... |
Sniff packets and return a list of packets.
Args:
count: number of packets to capture. 0 means infinity.
store: whether to store sniffed packets or discard them
prn: function to apply to each packet. If something is returned, it
is displayed.
--Ex: prn = lambda x: ... |
Forward traffic between interfaces if1 and if2, sniff and return
the exchanged packets.
Arguments:
if1, if2: the interfaces to use (interface names or opened sockets).
xfrm12: a function to call when forwarding a packet from if1 to
if2. If it returns True, the packet is forwarded as it. If it
returns... |
Sniff packets and print them calling pkt.summary(), a bit like text wireshark
def tshark(*args, **kargs):
"""Sniff packets and print them calling pkt.summary(), a bit like text wireshark""" # noqa: E501
print("Capturing on '" + str(kargs.get('iface') if 'iface' in kargs else conf.iface) + "'") # noqa: E501
... |
Send a IKEv2 SA to an IP and wait for answers.
def ikev2scan(ip, **kwargs):
"""Send a IKEv2 SA to an IP and wait for answers."""
return sr(IP(dst=ip) / UDP() / IKEv2(init_SPI=RandString(8),
exch_type=34) / IKEv2_payload_SA(prop=IKEv2_payload_Proposal()), **kwargs) |
Internal function used to register an OID and its name in a MIBDict
def _mib_register(ident, value, the_mib, unresolved):
"""Internal function used to register an OID and its name in a MIBDict"""
if ident in the_mib or ident in unresolved:
return ident in the_mib
resval = []
not_resolved = 0
... |
Load the conf.mib dict from a list of filenames
def load_mib(filenames):
"""Load the conf.mib dict from a list of filenames"""
the_mib = {'iso': ['1']}
unresolved = {}
for k in six.iterkeys(conf.mib):
_mib_register(conf.mib[k], k.split("."), the_mib, unresolved)
if isinstance(filenames, (s... |
Internal MIBDict function used to find a partial OID
def _findroot(self, x):
"""Internal MIBDict function used to find a partial OID"""
if x.startswith("."):
x = x[1:]
if not x.endswith("."):
x += "."
max = 0
root = "."
root_key = ""
for k... |
Parse the OID id/OID generator, and return real OID
def _oid(self, x):
"""Parse the OID id/OID generator, and return real OID"""
xl = x.strip(".").split(".")
p = len(xl) - 1
while p >= 0 and _mib_re_integer.match(xl[p]):
p -= 1
if p != 0 or xl[p] not in six.itervalue... |
get the total size of all under layers
:return: number of bytes
def _get_underlayers_size(self):
"""
get the total size of all under layers
:return: number of bytes
"""
under_layer = self.underlayer
under_layers_size = 0
while under_layer and isinstanc... |
add padding to the frame if required.
note that padding is only added if pay is None/empty. this allows us to add # noqa: E501
any payload after the MACControl* PDU if needed (piggybacking).
def post_build(self, pkt, pay):
"""
add padding to the frame if required.
note that p... |
get pause time for given link speed in seconds
:param speed: select link speed to get the pause time for, must be ETHER_SPEED_MBIT_[10,100,1000] # noqa: E501
:return: pause time in seconds
:raises MACControlInvalidSpeedException: on invalid speed selector
def get_pause_time(self, speed=ETHER_... |
Read a candump log file and return a packet list
count: read only <count> packets
is_not_log_file_format: read input with candumps stdout format
interfaces: return only packets from a specified interface
def rdcandump(filename, count=None,
is_not_log_file_format=False,
interface=None):
... |
Invert the order of the first four bytes of a CAN packet
This method is meant to be used specifically to convert a CAN packet
between the pcap format and the socketCAN format
:param pkt: str of the CAN packet
:return: packet str with the first four bytes swapped
def inv_endianness(pkt... |
Implements the swap-bytes functionality when building
this is based on a copy of the Packet.self_build default method.
The goal is to affect only the CAN layer data and keep
under layers (e.g LinuxCooked) unchanged
def post_build(self, pkt, pay):
""" Implements the swap-bytes functiona... |
Calculate the date the machine which emitted the packet booted using TCP timestamp # noqa: E501
pkt2uptime(pkt, [HZ=100])
def pkt2uptime(pkt, HZ=100):
"""Calculate the date the machine which emitted the packet booted using TCP timestamp # noqa: E501
pkt2uptime(pkt, [HZ=100])"""
if not isinstance(pkt, Packet)... |
Modifies pkt so that p0f will think it has been sent by a
specific OS. If osdetails is None, then we randomly pick up a
personality matching osgenre. If osgenre and signature are also None,
we use a local signature (using p0f_getlocalsigs). If signature is
specified (as a tuple), we use the signature.
For now, only T... |
Generate the response block of this request.
Careful: it only sets the fields which can be set from the request
def get_response(self):
"""Generate the response block of this request.
Careful: it only sets the fields which can be set from the request
"""
res = IODControlRes()
... |
Generate the response block of this request.
Careful: it only sets the fields which can be set from the request
def get_response(self):
"""Generate the response block of this request.
Careful: it only sets the fields which can be set from the request
"""
res = IODWriteRes()
... |
get the length of the field, including the padding length
def i2len(self, pkt, val):
"""get the length of the field, including the padding length"""
fld_len = self._fld.i2len(pkt, val)
return fld_len + self.padlen(fld_len) |
Generate the response block of this request.
Careful: it only sets the fields which can be set from the request
def get_response(self):
"""Generate the response block of this request.
Careful: it only sets the fields which can be set from the request
"""
res = IODWriteMultipleRe... |
Generate the response block of this request.
Careful: it only sets the fields which can be set from the request
def get_response(self):
"""Generate the response block of this request.
Careful: it only sets the fields which can be set from the request
"""
res = ARBlockRes()
... |
Generate the response block of this request.
Careful: it only sets the fields which can be set from the request
def get_response(self):
"""Generate the response block of this request.
Careful: it only sets the fields which can be set from the request
"""
res = IOCRBlockRes()
... |
heuristical guess_payload_class
def can_handle(cls, pkt, rpc):
"""heuristical guess_payload_class"""
# type = 0 => request
if rpc.getfieldval("type") == 0 and \
str(rpc.object_uuid).startswith("dea00000-6c97-11d1-8271-"):
return True
return False |
generate an IV for the packet
def make_iv(self, pkt):
"""generate an IV for the packet"""
if self.xpn_en:
tmp_pn = (self.pn & 0xFFFFFFFF00000000) | (pkt[MACsec].pn & 0xFFFFFFFF) # noqa: E501
tmp_iv = self.ssci + struct.pack('!Q', tmp_pn)
return bytes(bytearray([a ^ ... |
split the packet into associated data, plaintext or ciphertext, and
optional ICV
def split_pkt(pkt, assoclen, icvlen=0):
"""
split the packet into associated data, plaintext or ciphertext, and
optional ICV
"""
data = raw(pkt)
assoc = data[:assoclen]
if ic... |
encapsulate a frame using this Secure Association
def encap(self, pkt):
"""encapsulate a frame using this Secure Association"""
if pkt.name != Ether().name:
raise TypeError('cannot encapsulate packet in MACsec, must be Ethernet') # noqa: E501
hdr = copy.deepcopy(pkt)
payloa... |
decapsulate a MACsec frame
def decap(self, orig_pkt):
"""decapsulate a MACsec frame"""
if orig_pkt.name != Ether().name or orig_pkt.payload.name != MACsec().name: # noqa: E501
raise TypeError('cannot decapsulate MACsec packet, must be Ethernet/MACsec') # noqa: E501
packet = copy.d... |
encrypt a MACsec frame for this Secure Association
def encrypt(self, orig_pkt, assoclen=None):
"""encrypt a MACsec frame for this Secure Association"""
hdr = copy.deepcopy(orig_pkt)
del hdr[MACsec].payload
del hdr[MACsec].type
pktlen = len(orig_pkt)
if self.send_sci:
... |
decrypt a MACsec frame for this Secure Association
def decrypt(self, orig_pkt, assoclen=None):
"""decrypt a MACsec frame for this Secure Association"""
hdr = copy.deepcopy(orig_pkt)
del hdr[MACsec].payload
pktlen = len(orig_pkt)
if self.send_sci:
hdrlen = NOSCI_LEN +... |
send and receive using a bluetooth socket
def srbt(bt_address, pkts, inter=0.1, *args, **kargs):
"""send and receive using a bluetooth socket"""
if "port" in kargs:
s = conf.BTsocket(bt_address=bt_address, port=kargs.pop("port"))
else:
s = conf.BTsocket(bt_address=bt_address)
a, b = snd... |
send and receive 1 packet using a bluetooth socket
def srbt1(bt_address, pkts, *args, **kargs):
"""send and receive 1 packet using a bluetooth socket"""
a, b = srbt(bt_address, pkts, *args, **kargs)
if len(a) > 0:
return a[0][1] |
Registers a payload type that uses magic data.
Traditional payloads require registration of a Bluetooth Company ID
(requires company membership of the Bluetooth SIG), or a Bluetooth
Short UUID (requires a once-off payment).
There are alternatives which don't require registration (such ... |
Returns true if pkt is using SOMEIP-TP, else returns false.
def _is_tp(pkt):
"""Returns true if pkt is using SOMEIP-TP, else returns false."""
tp = [SOMEIP.TYPE_TP_REQUEST, SOMEIP.TYPE_TP_REQUEST_NO_RET,
SOMEIP.TYPE_TP_NOTIFICATION, SOMEIP.TYPE_TP_RESPONSE,
SOMEIP.TYPE_TP_E... |
Fragment SOME/IP-TP
def fragment(self, fragsize=1392):
"""Fragment SOME/IP-TP"""
fnb = 0
fl = self
lst = list()
while fl.underlayer is not None:
fnb += 1
fl = fl.underlayer
for p in fl:
s = raw(p[fnb].payload)
nb = (len(s)... |
Generates the next RadioTapExtendedPresenceMask
def _next_radiotap_extpm(pkt, lst, cur, s):
"""Generates the next RadioTapExtendedPresenceMask"""
if cur is None or (cur.present and cur.present.Ext):
st = len(lst) + (cur is not None)
return lambda *args: RadioTapExtendedPresenceMask(*args, index... |
Return a dictionary containing a summary of the Dot11
elements fields
def network_stats(self):
"""Return a dictionary containing a summary of the Dot11
elements fields
"""
summary = {}
crypto = set()
akmsuite_types = {
0x00: "Reserved",
0x... |
Get the correct source IP address of an interface alias
def get_alias_address(iface_name, ip_mask, gw_str, metric):
"""
Get the correct source IP address of an interface alias
"""
# Detect the architecture
if scapy.consts.IS_64BITS:
offset, name_len = 16, 40
else:
offset, name_... |
Returns a list of 3-tuples of the form (addr, scope, iface) where
'addr' is the address of scope 'scope' associated to the interface
'ifcace'.
This is the list of all addresses of all interfaces available on
the system.
def in6_getifaddr():
"""
Returns a list of 3-tuples of the form (addr, sco... |
Return the interface mode.
params:
- iface: the iwconfig interface
def get_iface_mode(iface):
"""Return the interface mode.
params:
- iface: the iwconfig interface
"""
p = subprocess.Popen(["iwconfig", iface], stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
... |
Sets the monitor mode (or remove it) from an interface.
params:
- iface: the iwconfig interface
- monitor: True if the interface should be set in monitor mode,
False if it should be in managed mode
def set_iface_monitor(iface, monitor):
"""Sets the monitor mode (or remove it) from an ... |
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
pkt, sa_ll = self.ins.recvfrom(x)
if self.outs and sa_ll[2] == socket.PACKET_OUTGOING:
ret... |
Return True is obj is a BPF Super Socket
def isBPFSocket(obj):
"""Return True is obj is a BPF Super Socket"""
return isinstance(obj, L2bpfListenSocket) or isinstance(obj, L2bpfListenSocket) or isinstance(obj, L3bpfSocket) |
A call to recv() can return several frames. This functions hides the fact
that some frames are read from the internal buffer.
def bpf_select(fds_list, timeout=None):
"""A call to recv() can return several frames. This functions hides the fact
that some frames are read from the internal buffer."""
... |
Set the interface in promiscuous mode
def set_promisc(self, value):
"""Set the interface in promiscuous mode"""
try:
fcntl.ioctl(self.ins, BIOCPROMISC, struct.pack('i', value))
except IOError:
raise Scapy_Exception("Cannot set promiscuous mode on interface "
... |
Guess the packet class that must be used on the interface
def guess_cls(self):
"""Guess the packet class that must be used on the interface"""
# Get the data link type
try:
ret = fcntl.ioctl(self.ins, BIOCGDLT, struct.pack('I', 0))
ret = struct.unpack('I', ret)[0]
... |
Set the non blocking flag on the socket
def set_nonblock(self, set_flag=True):
"""Set the non blocking flag on the socket"""
# Get the current flags
if self.fd_flags is None:
try:
self.fd_flags = fcntl.fcntl(self.ins, fcntl.F_GETFL)
except IOError:
... |
Get received / dropped statistics
def get_stats(self):
"""Get received / dropped statistics"""
try:
ret = fcntl.ioctl(self.ins, BIOCGSTATS, struct.pack("2I", 0, 0))
return struct.unpack("2I", ret)
except IOError:
warning("Unable to get stats from BPF !")
... |
Get the BPF buffer length
def get_blen(self):
"""Get the BPF buffer length"""
try:
ret = fcntl.ioctl(self.ins, BIOCGBLEN, struct.pack("I", 0))
return struct.unpack("I", ret)[0]
except IOError:
warning("Unable to get the BPF buffer length")
return |
Close the Super Socket
def close(self):
"""Close the Super Socket"""
if not self.closed and self.ins is not None:
os.close(self.ins)
self.closed = True
self.ins = None |
Extract all frames from the buffer and stored them in the received list.
def extract_frames(self, bpf_buffer):
"""Extract all frames from the buffer and stored them in the received list.""" # noqa: E501
# Ensure that the BPF buffer contains at least the header
len_bb = len(bpf_buffer)
... |
Receive a frame from the network
def recv(self, x=BPF_BUFFER_LENGTH):
"""Receive a frame from the network"""
if self.buffered_frames():
# Get a frame from the buffer
return self.get_frame()
# Get data from BPF
try:
bpf_buffer = os.read(self.ins, x)
... |
Non blocking receive
def nonblock_recv(self):
"""Non blocking receive"""
if self.buffered_frames():
# Get a frame from the buffer
return self.get_frame()
# Set the non blocking flag, read from the socket, and unset the flag
self.set_nonblock(True)
pkt =... |
Get a frame or packet from the received list
def get_frame(self):
"""Get a frame or packet from the received list"""
pkt = super(L3bpfSocket, self).get_frame()
if pkt is not None:
return pkt.payload |
Send a packet
def send(self, pkt):
"""Send a packet"""
# Use the routing table to find the output interface
iff = pkt.route()[0]
if iff is None:
iff = conf.iface
# Assign the network interface to the BPF handle
if self.assigned_interface != iff:
... |
Covers both post_build- and post_dissection- context updates.
def tls_session_update(self, msg_str):
"""
Covers both post_build- and post_dissection- context updates.
"""
self.tls_session.handshake_messages.append(msg_str)
self.tls_session.handshake_messages_parsed.append(self) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.