INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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=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... |
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... | def sendpfast(x, pps=None, mbps=None, realtime=None, loop=0, file_cache=False, iface=None, replay_args=None, # noqa: E501
parse_results=False):
"""Send packets at layer 2 using tcpreplay for performance
pps: packets per second
mpbs: MBits per second
realtime: use packet's timestamp, bend... |
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... | def _parse_tcpreplay_result(stdout, stderr, argv):
"""
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 tcp... |
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.close()
return result |
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, _ = sndrcv(s, x, *args, **kargs)
s.close()
if len... |
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.L2socket(promisc=promisc, iface=iface,
... |
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=None, *args, **kargs): # noqa: E501
"""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: ... |
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, iface=None, nofilter=0, *args, **kargs): # noqa: E501
"""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 ... |
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_hint=None, nofilter=None, *args, **kargs): # noqa: E501
"""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... |
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, iface=None, nofilter=0, *args, **kargs): # noqa: E501
"""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... |
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: ... | def sniff(count=0, store=True, offline=None, prn=None, lfilter=None,
L2socket=None, timeout=None, opened_socket=None,
stop_filter=None, iface=None, started_callback=None,
session=None, *arg, **karg):
"""Sniff packets and return a list of packets.
Args:
count: number of pac... |
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... | def bridge_and_sniff(if1, if2, xfrm12=None, xfrm21=None, prn=None, L2socket=None, # noqa: E501
*args, **kargs):
"""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).
xfrm... |
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
i = [0] # This should be a nonlocal variable, using a mutable object for Py... |
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
for v in value:
if _mib_re_integer.match(v):
re... |
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, (str, bytes)):
filenames = [filenames]
... |
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 in six.iterkeys(self):
if x.startswith(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.itervalues(self.__dict__):
return x
xl[p] ... |
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 isinstance(under_layer, Dot1Q):
under_layers_size += 4
und... |
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 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).
"""
if not pay:
under_layers_s... |
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_SPEED_MBIT_1000):
"""
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 MACControlInvalidSpeed... |
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):
"""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 interfa... |
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):
""" 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 ... |
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 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
"""
if conf.contribs... |
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):
raise TypeError("Not a TCP packet")
if isinstance(pkt, NoPayload):
raise TypeError("Not a TCP 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... | def p0f_impersonate(pkt, osgenre=None, osdetails=None, signature=None,
extrahops=0, mtu=1500, uptime=None):
"""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 ... |
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()
for field in ["ARUUID", "SessionKey", "AlarmSequenceNumber"]:
res.setfieldval(field, self.getfieldval(f... |
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()
for field in ["seqNum", "ARUUID", "API", "slotNumber",
"subslotNumber", "index"]:
r... |
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 = IODWriteMultipleRes()
for field in ["seqNum", "ARUUID", "API", "slotNumber",
"subslotNumber", "index"]:
... |
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()
for field in ["ARType", "ARUUID", "SessionKey"]:
res.setfieldval(field, self.getfieldval(field))
r... |
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()
for field in ["IOCRType", "IOCRReference", "FrameID"]:
res.setfieldval(field, self.getfieldval(field))
... |
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 ^ b for a, b in zip(bytearray(tmp... |
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 icvlen:
icv = data[-icvlen:]
enc = data[assoclen:-icvlen]
el... |
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)
payload = hdr.payload
del hdr.payload
tag... |
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.deepcopy(orig_pkt)
pr... |
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:
hdrlen = NOSCI_LEN + SCI_LEN
else:
... |
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 + SCI_LEN
else:
hdrlen = NOSCI_LE... |
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 = sndrcv(s, pkts, inter=inter, *args, **kargs)
... |
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 ... | def register_magic_payload(cls, payload_cls, magic_check=None):
"""
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-o... |
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_ERROR]
if isinstance(pkt, Packet):
return ... |
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) + fragsize) // frags... |
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=st)
return None |
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",
0x01: "802.1X",
0x02: "PSK"
}
p = self.payload
... |
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_len = 32, 32
# Retrieve interfaces structures
sc... |
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, 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.
"""
ret = []
try:
fdesc = open... |
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)
output, err = p.communicate()
match = re.search(br"mode:([a-zA-Z]*)", out... |
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 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
"""
mode = get_iface_mode(iface)
i... |
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:
return None, None, None
ts = get_last_packet_timestamp(self.ins)
... |
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."""
# Check file descriptors types
bpf_scks_buffered = list()
select_fds = list()
for tmp_fd in fds_list:
# Specif... |
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 "
"(%s)!" % self.i... |
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]
except IOError:
cls = conf.default_l2
... |
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:
warning("Cannot get flags on t... |
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 !")
return (None, None) |
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)
if len_bb < 20: # Note: 20 == sizeof(struct bfp_hdr)
return
... |
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)
except EnvironmentError as... |
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 = L2bpfListenSocket.rec... |
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:
try:
... |
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) |
XXX Something should be done about the session ID here. | def tls_session_update(self, msg_str):
"""
XXX Something should be done about the session ID here.
"""
super(SSLv2ServerHello, self).tls_session_update(msg_str)
s = self.tls_session
client_cs = s.sslv2_common_cs
css = [cs for cs in client_cs if cs in self.ciphers... |
Generate a range object from (start, stop[, step]) tuples, or
return value. | def _get_values(value):
"""Generate a range object from (start, stop[, step]) tuples, or
return value.
"""
if (isinstance(value, tuple) and (2 <= len(value) <= 3) and
all(hasattr(i, "__int__") for i in value)):
# We use values[1] + 1 as stop value for (x)range to maintain
# ... |
psdump(filename=None, layer_shift=0, rebuild=1)
Creates an EPS file describing a packet. If filename is not provided a
temporary file is created and gs is called.
:param filename: the file's filename | def psdump(self, filename=None, **kargs):
"""
psdump(filename=None, layer_shift=0, rebuild=1)
Creates an EPS file describing a packet. If filename is not provided a
temporary file is created and gs is called.
:param filename: the file's filename
"""
from scapy.c... |
pdfdump(filename=None, layer_shift=0, rebuild=1)
Creates a PDF file describing a packet. If filename is not provided a
temporary file is created and xpdf is called.
:param filename: the file's filename | def pdfdump(self, filename=None, **kargs):
"""
pdfdump(filename=None, layer_shift=0, rebuild=1)
Creates a PDF file describing a packet. If filename is not provided a
temporary file is created and xpdf is called.
:param filename: the file's filename
"""
from scap... |
svgdump(filename=None, layer_shift=0, rebuild=1)
Creates an SVG file describing a packet. If filename is not provided a
temporary file is created and gs is called.
:param filename: the file's filename | def svgdump(self, filename=None, **kargs):
"""
svgdump(filename=None, layer_shift=0, rebuild=1)
Creates an SVG file describing a packet. If filename is not provided a
temporary file is created and gs is called.
:param filename: the file's filename
"""
from scapy... |
Extract description from README.md, for PyPI's usage | def get_long_description():
"""Extract description from README.md, for PyPI's usage"""
try:
fpath = os.path.join(os.path.dirname(__file__), "README.md")
with io.open(fpath, encoding="utf-8") as f:
readme = f.read()
desc = readme.partition("<!-- start_ppi_description -->")... |
Check for odd packet length and pad according to Cisco spec.
This padding is only used for checksum computation. The original
packet should not be altered. | def _check_len(self, pkt):
"""Check for odd packet length and pad according to Cisco spec.
This padding is only used for checksum computation. The original
packet should not be altered."""
if len(pkt) % 2:
last_chr = pkt[-1]
if last_chr <= b'\x80':
... |
Legacy method for PKCS1 v1.5 encoding with MD5-SHA1 hash. | def _legacy_pkcs1_v1_5_encode_md5_sha1(M, emLen):
"""
Legacy method for PKCS1 v1.5 encoding with MD5-SHA1 hash.
"""
M = bytes_encode(M)
md5_hash = hashes.Hash(_get_hash("md5"), backend=default_backend())
md5_hash.update(M)
sha1_hash = hashes.Hash(_get_hash("sha1"), backend=default_backend())... |
Send a DHCP discover request and return the answer | def dhcp_request(iface=None, **kargs):
"""Send a DHCP discover request and return the answer"""
if conf.checkIPaddr != 0:
warning("conf.checkIPaddr is not 0, I may not be able to match the answer") # noqa: E501
if iface is None:
iface = conf.iface
fam, hw = get_if_raw_hwaddr(iface)
... |
Updates the specified IPython console shell with
the conf.color_theme scapy theme. | def apply_ipython_style(shell):
"""Updates the specified IPython console shell with
the conf.color_theme scapy theme."""
try:
from IPython.terminal.prompts import Prompts, Token
except Exception:
from scapy.error import log_loading
log_loading.warning(
"IPython too ol... |
This get started as a thread, and waits for the data lock to be freed then advertise itself to the SelectableSelector using the callback | def _wait_non_ressources(self, callback):
"""This get started as a thread, and waits for the data lock to be freed then advertise itself to the SelectableSelector using the callback""" # noqa: E501
self.trigger = threading.Lock()
self.was_ended = False
self.trigger.acquire()
sel... |
Entry point of SelectableObject: register the callback | def wait_return(self, callback):
"""Entry point of SelectableObject: register the callback"""
if self.check_recv():
return callback(self)
_t = threading.Thread(target=self._wait_non_ressources, args=(callback,)) # noqa: E501
_t.setDaemon(True)
_t.start() |
DEV: Must be call when the object becomes ready to read.
Relesases the lock of _wait_non_ressources | def call_release(self, arborted=False):
"""DEV: Must be call when the object becomes ready to read.
Relesases the lock of _wait_non_ressources"""
self.was_ended = arborted
try:
self.trigger.release()
except (threading.ThreadError, AttributeError):
pass |
Releases all locks to kill all threads | def _release_all(self):
"""Releases all locks to kill all threads"""
for i in self.inputs:
i.call_release(True)
self.available_lock.release() |
Timeout before releasing every thing, if nothing was returned | def _timeout_thread(self, remain):
"""Timeout before releasing every thing, if nothing was returned"""
time.sleep(remain)
if not self._ended:
self._ended = True
self._release_all() |
This function is passed to each SelectableObject as a callback
The SelectableObjects have to call it once there are ready | def _exit_door(self, _input):
"""This function is passed to each SelectableObject as a callback
The SelectableObjects have to call it once there are ready"""
self.results.append(_input)
if self._ended:
return
self._ended = True
self._release_all() |
Entry point of SelectableSelector | def process(self):
"""Entry point of SelectableSelector"""
if WINDOWS:
select_inputs = []
for i in self.inputs:
if not isinstance(i, SelectableObject):
warning("Unknown ignored object type: %s", type(i))
elif i.__selectable_forc... |
Checks that module has a higher version that minver.
params:
- module: a module to test
- minver: a tuple of versions | def _version_checker(module, minver):
"""Checks that module has a higher version that minver.
params:
- module: a module to test
- minver: a tuple of versions
"""
# We could use LooseVersion, but distutils imports imp which is deprecated
version_regexp = r'[a-z]?((?:\d|\.)+\d+)(?:\.dev[0-... |
Check if the cryptography library is present, and if it supports X25519,
ChaCha20Poly1305 and such (v2.0 or later). | def isCryptographyAdvanced():
"""
Check if the cryptography library is present, and if it supports X25519,
ChaCha20Poly1305 and such (v2.0 or later).
"""
try:
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey # noqa: E501
X25519PrivateKey.generate()
e... |
Change the current prompt theme | def _prompt_changer(attr, val):
"""Change the current prompt theme"""
try:
sys.ps1 = conf.color_theme.prompt(conf.prompt)
except Exception:
pass
try:
apply_ipython_style(get_ipython())
except NameError:
pass |
Populate the conf.L2Socket and conf.L3Socket
according to the various use_* parameters | def _set_conf_sockets():
"""Populate the conf.L2Socket and conf.L3Socket
according to the various use_* parameters
"""
if conf.use_bpf and not BSD:
Interceptor.set_from_hook(conf, "use_bpf", False)
raise ScapyInvalidPlatformException("BSD-like (OSX, *BSD...) only !")
if conf.use_winp... |
This a decorator to be used for any method relying on the cryptography library. # noqa: E501
Its behaviour depends on the 'crypto_valid' attribute of the global 'conf'. | def crypto_validator(func):
"""
This a decorator to be used for any method relying on the cryptography library. # noqa: E501
Its behaviour depends on the 'crypto_valid' attribute of the global 'conf'.
"""
def func_in(*args, **kwargs):
if not conf.crypto_valid:
raise ImportError(... |
Returns a packet list filtered by a truth function. This truth
function has to take a packet as the only argument and return a boolean value. | def filter(self, func):
"""Returns a packet list filtered by a truth function. This truth
function has to take a packet as the only argument and return a boolean value.""" # noqa: E501
return self.__class__([x for x in self.res if func(x)],
name="filtered %s" % sel... |
Applies a function to each packet to get a value that will be plotted
with matplotlib. A list of matplotlib.lines.Line2D is returned.
lfilter: a truth function that decides whether a packet must be plotted | def plot(self, f, lfilter=None, plot_xy=False, **kargs):
"""Applies a function to each packet to get a value that will be plotted
with matplotlib. A list of matplotlib.lines.Line2D is returned.
lfilter: a truth function that decides whether a packet must be plotted
"""
# Python... |
diffplot(f, delay=1, lfilter=None)
Applies a function to couples (l[i],l[i+delay])
A list of matplotlib.lines.Line2D is returned. | def diffplot(self, f, delay=1, lfilter=None, **kargs):
"""diffplot(f, delay=1, lfilter=None)
Applies a function to couples (l[i],l[i+delay])
A list of matplotlib.lines.Line2D is returned.
"""
# Get the list of packets
if lfilter is None:
lst_pkts = [f(self.r... |
Uses a function that returns a label and a value for this label, then
plots all the values label by label.
A list of matplotlib.lines.Line2D is returned. | def multiplot(self, f, lfilter=None, plot_xy=False, **kargs):
"""Uses a function that returns a label and a value for this label, then
plots all the values label by label.
A list of matplotlib.lines.Line2D is returned.
"""
# Python 2 backward compatibility
f = lambda_tu... |
Same as nsummary(), except that if a packet has a Raw layer, it will be hexdumped # noqa: E501
lfilter: a truth function that decides whether a packet must be displayed | def hexraw(self, lfilter=None):
"""Same as nsummary(), except that if a packet has a Raw layer, it will be hexdumped # noqa: E501
lfilter: a truth function that decides whether a packet must be displayed""" # noqa: E501
for i, res in enumerate(self.res):
p = self._elt2pkt(res)
... |
Same as nsummary(), except that packets are also hexdumped
lfilter: a truth function that decides whether a packet must be displayed | def hexdump(self, lfilter=None):
"""Same as nsummary(), except that packets are also hexdumped
lfilter: a truth function that decides whether a packet must be displayed""" # noqa: E501
for i, res in enumerate(self.res):
p = self._elt2pkt(res)
if lfilter is not None and n... |
Graphes a conversations between sources and destinations and display it
(using graphviz and imagemagick)
getsrcdst: a function that takes an element of the list and
returns the source, the destination and optionally
a label. By default, returns the IP source and
... | def conversations(self, getsrcdst=None, **kargs):
"""Graphes a conversations between sources and destinations and display it
(using graphviz and imagemagick)
getsrcdst: a function that takes an element of the list and
returns the source, the destination and optionally
... |
Experimental clone attempt of http://sourceforge.net/projects/afterglow
each datum is reduced as src -> event -> dst and the data are graphed.
by default we have IP.src -> IP.dport -> IP.dst | def afterglow(self, src=None, event=None, dst=None, **kargs):
"""Experimental clone attempt of http://sourceforge.net/projects/afterglow
each datum is reduced as src -> event -> dst and the data are graphed.
by default we have IP.src -> IP.dport -> IP.dst"""
if src is None:
s... |
sr([multi=1]) -> (SndRcvList, PacketList)
Matches packets in the list and return ( (matched couples), (unmatched packets) ) | def sr(self, multi=0):
"""sr([multi=1]) -> (SndRcvList, PacketList)
Matches packets in the list and return ( (matched couples), (unmatched packets) )""" # noqa: E501
remain = self.res[:]
sr = []
i = 0
while i < len(remain):
s = remain[i]
j = i
... |
lst.replace(<field>,[<oldvalue>,]<newvalue>)
lst.replace( (fld,[ov],nv),(fld,[ov,]nv),...)
if ov is None, all values are replaced
ex:
lst.replace( IP.src, "192.168.1.1", "10.0.0.1" )
lst.replace( IP.ttl, 64 )
lst.replace( (IP.ttl, 64), (TCP.sport, 666, 777), ) | def replace(self, *args, **kargs):
"""
lst.replace(<field>,[<oldvalue>,]<newvalue>)
lst.replace( (fld,[ov],nv),(fld,[ov,]nv),...)
if ov is None, all values are replaced
ex:
lst.replace( IP.src, "192.168.1.1", "10.0.0.1" )
lst.replace( IP.ttl, 64 )
... |
Return True if the tcpdump command can be started | def _check_tcpdump():
"""
Return True if the tcpdump command can be started
"""
with open(os.devnull, 'wb') as devnull:
try:
proc = subprocess.Popen([conf.prog.tcpdump, "--version"],
stdout=devnull, stderr=subprocess.STDOUT)
except OSError:... |
Ease SIOCGIF* ioctl calls | def get_if(iff, cmd):
"""Ease SIOCGIF* ioctl calls"""
sck = socket.socket()
ifreq = ioctl(sck, cmd, struct.pack("16s16x", iff.encode("utf8")))
sck.close()
return ifreq |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.