INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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. | def isRevoked(self, crl_list):
"""
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... |
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":
f.write(self.pem)
f.close() |
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 will be retained. Eventually dat... | def verifyChain(self, anchors, untrusted=None):
"""
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 instantiati... |
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 using the list of anchors
from the cafile. As for .verifyChain(), a list of untrusted
certificates can be passed (as a file, this time).
"""
try:
f = open... |
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 certificates in PEM format ). | def verifyChainFromCAPath(self, capath, untrusted_file=None):
"""
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 untr... |
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_id == other.service)
return False |
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 emission:")
for p in tobesent:
# ... |
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)
ans = []
def _get_pkt():
# SuperSocket.sele... |
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,
process=None, prebuild=False):
"""Scapy raw function to send a packet and receive its answer.
WARNING: This is an internal function. Using sr/srp/sr1/srp is
... |
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 3
send(packets, [inter=0], [loop=0], [count=None], [verbose=conf.verb], [realtime=None], [return_packets=False], # noqa: E501
[socket=None]) -> N... |
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 # noqa: E501 iface:... | 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 subprocess call:... | 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. | 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. | 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. | 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 | 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 | 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 | 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 | 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. | 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. | 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. | 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 ) | 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 ) | 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 ) | 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. | 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. | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.