code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
@functools.wraps(func)
def behold(file, length, *args, **kwargs):
seek_cur = file.tell()
try:
return func(file, length, *args, **kwargs)
except Exception:
# from pcapkit.foundation.analysis import analyse
from pcapkit.protocols.raw import Raw
error = traceback.format_exc(limit=1).strip().split(os.linesep)[-1]
# error = traceback.format_exc()
file.seek(seek_cur, os.SEEK_SET)
# raw = Raw(file, length, error=str(error))
# return analyse(raw.info, raw.protochain, raw.alias)
next_ = Raw(file, length, error=error)
return next_
return behold | def beholder_ng(func) | Behold analysis procedure. | 3.947007 | 4.017052 | 0.982563 |
if length is None:
length = len(self)
_flag = self._read_binary(1)
_vers = self._read_fileng(1).hex()[1]
_hlen = self._read_unpack(2) if int(_flag[1]) else None
_tnnl = self._read_unpack(2)
_sssn = self._read_unpack(2)
_nseq = self._read_unpack(2) if int(_flag[4]) else None
_nrec = self._read_unpack(2) if int(_flag[4]) else None
_size = self._read_unpack(2) if int(_flag[6]) else 0
l2tp = dict(
flags=dict(
type='Control' if int(_flag[0]) else 'Data',
len=True if int(_flag[1]) else False,
seq=True if int(_flag[4]) else False,
offset=True if int(_flag[6]) else False,
prio=True if int(_flag[7]) else False,
),
ver=int(_vers, base=16),
length=_hlen,
tunnelid=_tnnl,
sessionid=_sssn,
ns=_nseq,
nr=_nrec,
offset=8*_size or None,
)
hdr_len = _hlen or (6 + 2*(int(_flag[1]) + 2*int(_flag[4]) + int(_flag[6])))
l2tp['hdr_len'] = hdr_len + _size * 8
# if _size:
# l2tp['padding'] = self._read_fileng(_size * 8)
length -= l2tp['hdr_len']
l2tp['packet'] = self._read_packet(header=l2tp['hdr_len'], payload=length)
return self._decode_next_layer(l2tp, length) | def read_l2tp(self, length) | Read Layer Two Tunnelling Protocol.
Structure of L2TP header [RFC 2661]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|T|L|x|x|S|x|O|P|x|x|x|x| Ver | Length (opt) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Tunnel ID | Session ID |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Ns (opt) | Nr (opt) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Offset Size (opt) | Offset pad... (opt)
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 l2tp.flags Flags and Version Info
0 0 l2tp.flags.type Type (0/1)
0 1 l2tp.flags.len Length
0 2 - Reserved (must be zero)
0 4 l2tp.flags.seq Sequence
0 5 - Reserved (must be zero)
0 6 l2tp.flags.offset Offset
0 7 l2tp.flags.prio Priority
1 8 - Reserved (must be zero)
1 12 l2tp.ver Version (2)
2 16 l2tp.length Length (optional by len)
4 32 l2tp.tunnelid Tunnel ID
6 48 l2tp.sessionid Session ID
8 64 l2tp.ns Sequence Number (optional by seq)
10 80 l2tp.nr Next Sequence Number (optional by seq)
12 96 l2tp.offset Offset Size (optional by offset) | 3.370874 | 2.776688 | 1.213991 |
if isinstance(key, int):
return ECDSA_LOW_Curve(key)
if key not in ECDSA_LOW_Curve._member_map_:
extend_enum(ECDSA_LOW_Curve, key, default)
return ECDSA_LOW_Curve[key] | def get(key, default=-1) | Backport support for original codes. | 5.136911 | 4.680596 | 1.097491 |
if isinstance(key, int):
return Hardware(key)
if key not in Hardware._member_map_:
extend_enum(Hardware, key, default)
return Hardware[key] | def get(key, default=-1) | Backport support for original codes. | 6.366552 | 5.520733 | 1.153208 |
if length is None:
length = len(self)
_tcif = self._read_binary(2)
_type = self._read_protos(2)
vlan = dict(
tci=dict(
pcp=_PCP.get(int(_tcif[:3], base=2)),
dei=True if _tcif[3] else False,
vid=int(_tcif[4:], base=2),
),
type=_type,
)
length -= 4
vlan['packet'] = self._read_packet(header=4, payload=length)
return self._decode_next_layer(vlan, _type, length) | def read_vlan(self, length) | Read 802.1Q Customer VLAN Tag Type.
Structure of 802.1Q Customer VLAN Tag Type [RFC 7042]:
Octets Bits Name Description
1 0 vlan.tci Tag Control Information
1 0 vlan.tci.pcp Priority Code Point
1 3 vlan.tci.dei Drop Eligible Indicator
1 4 vlan.tci.vid VLAN Identifier
3 24 vlan.type Protocol (Internet Layer) | 5.319366 | 4.286148 | 1.24106 |
if isinstance(key, int):
return TaggerId(key)
if key not in TaggerId._member_map_:
extend_enum(TaggerId, key, default)
return TaggerId[key] | def get(key, default=-1) | Backport support for original codes. | 5.11918 | 4.479421 | 1.142822 |
counter = 0 # length of read option list
optkind = list() # option kind list
options = dict() # dict of option data
while counter < size:
# get option kind
kind = self._read_unpack(1)
# fetch corresponding option tuple
opts = TCP_OPT.get(kind)
enum = OPT_TYPE.get(kind)
if opts is None:
len_ = size - counter
counter = size
optkind.append(enum)
options[enum.name] = self._read_fileng(len_)
break
# extract option
dscp = opts[1]
if opts[0]:
len_ = self._read_unpack(1)
byte = opts[2](len_)
if byte: # check option process mode
data = process_opt[opts[3]](self, byte, kind)
else: # permission options (length is 2)
data = dict(
kind=kind, # option kind
length=2, # option length
flag=True, # permission flag
)
else: # 1-bytes options
len_ = 1
data = dict(
kind=kind, # option kind
length=1, # option length
)
# record option data
counter += len_
if enum in optkind:
if isinstance(options[dscp], tuple):
options[dscp] += (Info(data),)
else:
options[dscp] = (Info(options[dscp]), Info(data))
else:
optkind.append(enum)
options[dscp] = data
# break when eol triggered
if not kind:
break
# get padding
if counter < size:
len_ = size - counter
options['padding'] = self._read_fileng(len_)
return tuple(optkind), options | def _read_tcp_options(self, size) | Read TCP option list.
Positional arguments:
* size -- int, length of option list
Returns:
* tuple -- TCP option list
* dict -- extracted TCP option | 4.618124 | 4.505614 | 1.024971 |
data = dict(
kind=kind,
length=size,
data=self._read_fileng(size),
)
return data | def _read_mode_donone(self, size, kind) | Read options request no process.
Positional arguments:
* size - int, length of option
* kind - int, option kind value
Returns:
* dict -- extracted option with no operation
Structure of TCP options:
Octets Bits Name Description
0 0 tcp.opt.kind Kind
1 8 tcp.opt.length Length
2 16 tcp.opt.data Kind-specific Data | 6.404864 | 6.898539 | 0.928438 |
data = dict(
kind=kind,
length=size,
data=self._read_unpack(size),
)
return data | def _read_mode_unpack(self, size, kind) | Read options request unpack process.
Keyword arguments:
size - int, length of option
kind - int, option kind value
Returns:
* dict -- extracted option which unpacked
Structure of TCP options:
Octets Bits Name Description
0 0 tcp.opt.kind Kind
1 8 tcp.opt.length Length
2 16 tcp.opt.data Kind-specific Data | 4.963257 | 5.06686 | 0.979553 |
temp = struct.unpack('>II', self._read_fileng(size))
data = dict(
kind=kind,
length=size,
val=temp[0],
ecr=temp[1],
)
return data | def _read_mode_tsopt(self, size, kind) | Read Timestamps option.
Positional arguments:
* size - int, length of option
* kind - int, 8 (Timestamps)
Returns:
* dict -- extracted Timestamps (TS) option
Structure of TCP TSopt [RFC 7323]:
+-------+-------+---------------------+---------------------+
|Kind=8 | 10 | TS Value (TSval) |TS Echo Reply (TSecr)|
+-------+-------+---------------------+---------------------+
1 1 4 4
Octets Bits Name Description
0 0 tcp.ts.kind Kind (8)
1 8 tcp.ts.length Length (10)
2 16 tcp.ts.val Timestamp Value
6 48 tcp.ts.ecr Timestamps Echo Reply | 6.648014 | 4.858887 | 1.368217 |
temp = self._read_binary(size)
data = dict(
kind=kind,
length=size,
start=True if int(temp[0]) else False,
end=True if int(temp[1]) else False,
filler=bytes(chr(int(temp[2:], base=2)), encoding='utf-8'),
)
return data | def _read_mode_pocsp(self, size, kind) | Read Partial Order Connection Service Profile option.
Positional arguments:
* size - int, length of option
* kind - int, 10 (POC-Serv Profile)
Returns:
* dict -- extracted Partial Order Connection Service Profile (POC-SP) option
Structure of TCP POC-SP Option [RFC 1693][RFC 6247]:
1 bit 1 bit 6 bits
+----------+----------+------------+----------+--------+
| Kind=10 | Length=3 | Start_flag | End_flag | Filler |
+----------+----------+------------+----------+--------+
Octets Bits Name Description
0 0 tcp.pocsp.kind Kind (10)
1 8 tcp.pocsp.length Length (3)
2 16 tcp.pocsp.start Start Flag
2 17 tcp.pocsp.end End Flag
2 18 tcp.pocsp.filler Filler | 4.752055 | 3.414111 | 1.391887 |
temp = self._read_unpack(size)
algo = chksum_opt.get(temp)
data = dict(
kind=kind,
length=size,
ac=algo,
)
return data | def _read_mode_acopt(self, size, kind) | Read Alternate Checksum Request option.
Positional arguments:
size - int, length of option
kind - int, 14 (Alt-Chksum Request)
Returns:
* dict -- extracted Alternate Checksum Request (CHKSUM-REQ) option
Structure of TCP CHKSUM-REQ [RFC 1146][RFC 6247]:
+----------+----------+----------+
| Kind=14 | Length=3 | chksum |
+----------+----------+----------+
Octets Bits Name Description
0 0 tcp.chksumreq.kind Kind (14)
1 8 tcp.chksumreq.length Length (3)
2 16 tcp.chksumreq.ac Checksum Algorithm | 12.127742 | 8.542841 | 1.419638 |
rvrr = self._read_binary(1)
ttld = self._read_unpack(1)
noun = self._read_fileng(4)
data = dict(
kind=kind,
length=size,
req_rate=int(rvrr[4:], base=2),
ttl_diff=ttld,
nounce=noun[:-2],
)
return data | def _read_mode_qsopt(self, size, kind) | Read Quick-Start Response option.
Positional arguments:
* size - int, length of option
* kind - int, 27 (Quick-Start Response)
Returns:
* dict -- extracted Quick-Start Response (QS) option
Structure of TCP QSopt [RFC 4782]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Kind | Length=8 | Resv. | Rate | TTL Diff |
| | | |Request| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| QS Nonce | R |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 tcp.qs.kind Kind (27)
1 8 tcp.qs.length Length (8)
2 16 - Reserved (must be zero)
2 20 tcp.qs.req_rate Request Rate
3 24 tcp.qs.ttl_diff TTL Difference
4 32 tcp.qs.nounce QS Nounce
7 62 - Reserved (must be zero) | 9.897898 | 5.870749 | 1.685969 |
temp = self._read_fileng(size)
data = dict(
kind=kind,
length=size,
granularity='minutes' if int(temp[0]) else 'seconds',
timeout=bytes(chr(int(temp[0:], base=2)), encoding='utf-8'),
)
return data | def _read_mode_utopt(self, size, kind) | Read User Timeout option.
Positional arguments:
* size - int, length of option
* kind - int, 28 (User Timeout Option)
Returns:
* dict -- extracted User Timeout (TIMEOUT) option
Structure of TCP TIMEOUT [RFC 5482]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Kind = 28 | Length = 4 |G| User Timeout |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 tcp.timeout.kind Kind (28)
1 8 tcp.timeout.length Length (4)
2 16 tcp.timeout.granularity Granularity
2 17 tcp.timeout.timeout User Timeout | 10.700179 | 6.951555 | 1.53925 |
key_ = self._read_unpack(1)
rkey = self._read_unpack(1)
mac_ = self._read_fileng(size - 2)
data = dict(
kind=kind,
length=size,
keyid=key_,
rnextkeyid=rkey,
mac=mac_,
)
return data | def _read_mode_tcpao(self, size, kind) | Read Authentication option.
Positional arguments:
* size - int, length of option
* kind - int, 29 (TCP Authentication Option)
Returns:
* dict -- extracted Authentication (AO) option
Structure of TCP AOopt [RFC 5925]:
+------------+------------+------------+------------+
| Kind=29 | Length | KeyID | RNextKeyID |
+------------+------------+------------+------------+
| MAC ...
+-----------------------------------...
...-----------------+
... MAC (con't) |
...-----------------+
Octets Bits Name Description
0 0 tcp.ao.kind Kind (29)
1 8 tcp.ao.length Length
2 16 tcp.ao.keyid KeyID
3 24 tcp.ao.rnextkeyid RNextKeyID
4 32 tcp.ao.mac Message Authentication Code | 5.85088 | 3.745511 | 1.562105 |
bins = self._read_binary(1)
subt = int(bins[:4], base=2) # subtype number
bits = bins[4:] # 4-bit data
dlen = size - 1 # length of remaining data
# fetch subtype-specific data
func = mptcp_opt.get(subt)
if func is None: # if subtype not exist, directly read all data
temp = self._read_fileng(dlen)
data = dict(
kind=kind,
length=size,
subtype='Unknown',
data=bytes(chr(int(bits[:4], base=2)), encoding='utf-8') + temp,
)
else: # fetch corresponding subtype data dict
data = func(self, bits, dlen, kind)
return data | def _read_mode_mptcp(self, size, kind) | Read Multipath TCP option.
Positional arguments:
* size - int, length of option
* kind - int, 30 (Multipath TCP)
Returns:
* dict -- extracted Multipath TCP (MP-TCP) option
Structure of MP-TCP [RFC 6824]:
1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+---------------+---------------+-------+-----------------------+
| Kind | Length |Subtype| |
+---------------+---------------+-------+ |
| Subtype-specific data |
| (variable length) |
+---------------------------------------------------------------+
Octets Bits Name Description
0 0 tcp.mp.kind Kind (30)
1 8 tcp.mp.length Length
2 16 tcp.mp.subtype Subtype
2 20 tcp.mp.data Subtype-specific Data | 6.885952 | 6.112065 | 1.126616 |
vers = int(bits, base=2)
bins = self._read_binary(1)
skey = self._read_fileng(8)
rkey = self._read_fileng(8) if size == 17 else None
data = dict(
kind=kind,
length=size + 1,
subtype='MP_CAPABLE',
capable=dict(
version=vers,
flags=dict(
req=True if int(bins[0]) else False,
ext=True if int(bins[1]) else False,
res=bytes(chr(int(bits[2:7], base=2)), encoding='utf-8'),
hsa=True if int(bins[7]) else False,
),
skey=skey,
rkey=rkey,
),
)
return data | def _read_mptcp_capable(self, bits, size, kind) | Read Multipath Capable option.
Positional arguments:
* bits - str, 4-bit data
* size - int, length of option
* kind - int, 30 (Multipath TCP)
Returns:
* dict -- extracted Multipath Capable (MP_CAPABLE) option
Structure of MP_CAPABLE [RFC 6824]:
1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+---------------+---------------+-------+-------+---------------+
| Kind | Length |Subtype|Version|A|B|C|D|E|F|G|H|
+---------------+---------------+-------+-------+---------------+
| Option Sender's Key (64 bits) |
| |
| |
+---------------------------------------------------------------+
| Option Receiver's Key (64 bits) |
| (if option Length == 20) |
| |
+---------------------------------------------------------------+
Octets Bits Name Description
0 0 tcp.mp.kind Kind (30)
1 8 tcp.mp.length Length (12/20)
2 16 tcp.mp.subtype Subtype (0)
2 20 tcp.mp.capable.version Version
3 24 tcp.mp.capable.flags.req Checksum Require Flag (A)
3 25 tcp.mp.capable.flags.ext Extensibility Flag (B)
3 26 tcp.mp.capable.flags.res Unassigned (C-G)
3 31 tcp.mp.capable.flags.hsa HMAC-SHA1 Flag (H)
4 32 tcp.mp.capable.skey Option Sender's Key
12 96 tcp.mp.capable.rkey Option Receiver's Key
(if option Length == 20) | 4.417034 | 3.031093 | 1.457241 |
if self._syn and self._ack: # MP_JOIN-SYN/ACK
return self._read_join_synack(bits, size, kind)
elif self._syn: # MP_JOIN-SYN
return self._read_join_syn(bits, size, kind)
elif self._ack: # MP_JOIN-ACK
return self._read_join_ack(bits, size, kind)
else: # illegal MP_JOIN occurred
temp = self._read_fileng(size)
data = dict(
kind=kind,
length=size + 1,
subtype='MP_JOIN-Unknown',
data=bytes(chr(int(bits[:4], base=2)), encoding='utf-8') + temp,
)
return data | def _read_mptcp_join(self, bits, size, kind) | Read Join Connection option.
Positional arguments:
* bits - str, 4-bit data
* size - int, length of option
* kind - int, 30 (Multipath TCP)
Returns:
* dict -- extracted Join Connection (MP_JOIN) option
Structure of MP_JOIN [RFC 6824]:
Octets Bits Name Description
0 0 tcp.mp.kind Kind (30)
1 8 tcp.mp.length Length
2 16 tcp.mp.subtype Subtype (1)
2 20 tcp.mp.data Handshake-specific Data | 3.819258 | 3.428034 | 1.114125 |
adid = self._read_unpack(1)
rtkn = self._read_fileng(4)
srno = self._read_unpack(4)
data = dict(
kind=kind,
length=size + 1,
subtype='MP_JOIN-SYN',
join=dict(
syn=dict(
backup=True if int(bits[3]) else False,
addrid=adid,
token=rtkn,
randnum=srno,
),
),
)
return data | def _read_join_syn(self, bits, size, kind) | Read Join Connection option for Initial SYN.
Positional arguments:
* bits - str, 4-bit data
* size - int, length of option
* kind - int, 30 (Multipath TCP)
Returns:
* dict -- extracted Join Connection (MP_JOIN-SYN) option for Initial SYN
Structure of MP_JOIN-SYN [RFC 6824]:
1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+---------------+---------------+-------+-----+-+---------------+
| Kind | Length = 12 |Subtype| |B| Address ID |
+---------------+---------------+-------+-----+-+---------------+
| Receiver's Token (32 bits) |
+---------------------------------------------------------------+
| Sender's Random Number (32 bits) |
+---------------------------------------------------------------+
Octets Bits Name Description
0 0 tcp.mp.kind Kind (30)
1 8 tcp.mp.length Length (12)
2 16 tcp.mp.subtype Subtype (1|SYN)
2 20 - Reserved (must be zero)
2 23 tcp.mp.join.syn.backup Backup Path (B)
3 24 tcp.mp.join.syn.addrid Address ID
4 32 tcp.mp.join.syn.token Receiver's Token
8 64 tcp.mp.join.syn.randnum Sender's Random Number | 7.569702 | 4.15241 | 1.822966 |
adid = self._read_unpack(1)
hmac = self._read_fileng(8)
srno = self._read_unpack(4)
data = dict(
kind=kind,
length=size + 1,
subtype='MP_JOIN-SYN/ACK',
join=dict(
synack=dict(
backup=True if int(bits[3]) else False,
addrid=adid,
hmac=hmac,
randnum=srno,
),
),
)
return data | def _read_join_synack(self, bits, size, kind) | Read Join Connection option for Responding SYN/ACK.
Positional arguments:
* bits - str, 4-bit data
* size - int, length of option
* kind - int, 30 (Multipath TCP)
Returns:
* dict -- extracted Join Connection (MP_JOIN-SYN/ACK) option for Responding SYN/ACK
Structure of MP_JOIN-SYN/ACK [RFC 6824]:
1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+---------------+---------------+-------+-----+-+---------------+
| Kind | Length = 16 |Subtype| |B| Address ID |
+---------------+---------------+-------+-----+-+---------------+
| |
| Sender's Truncated HMAC (64 bits) |
| |
+---------------------------------------------------------------+
| Sender's Random Number (32 bits) |
+---------------------------------------------------------------+
Octets Bits Name Description
0 0 tcp.mp.kind Kind (30)
1 8 tcp.mp.length Length (16)
2 16 tcp.mp.subtype Subtype (1|SYN/ACK)
2 20 - Reserved (must be zero)
2 23 tcp.mp.join.synack.backup Backup Path (B)
3 24 tcp.mp.join.synack.addrid Address ID
4 32 tcp.mp.join.synack.hmac Sender's Truncated HMAC
12 96 tcp.mp.join.synack.randnum Sender's Random Number | 7.392351 | 3.85339 | 1.918402 |
temp = self._read_fileng(20)
data = dict(
kind=kind,
length=size + 1,
subtype='MP_JOIN-ACK',
join=dict(
ack=dict(
hmac=temp,
),
),
)
return data | def _read_join_ack(self, bits, size, kind) | Read Join Connection option for Third ACK.
Positional arguments:
* bits - str, 4-bit data
* size - int, length of option
* kind - int, 30 (Multipath TCP)
Returns:
* dict -- extracted Join Connection (MP_JOIN-ACK) option for Third ACK
Structure of MP_JOIN-ACK [RFC 6824]:
1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+---------------+---------------+-------+-----------------------+
| Kind | Length = 24 |Subtype| (reserved) |
+---------------+---------------+-------+-----------------------+
| |
| |
| Sender's HMAC (160 bits) |
| |
| |
+---------------------------------------------------------------+
Octets Bits Name Description
0 0 tcp.mp.kind Kind (30)
1 8 tcp.mp.length Length (24)
2 16 tcp.mp.subtype Subtype (1|ACK)
2 20 - Reserved (must be zero)
4 32 tcp.mp.join.ack.hmac Sender's HMAC | 9.750667 | 5.353796 | 1.821262 |
vers = int(bits, base=2)
adid = self._read_unpack(1)
ipad = self._read_fileng(4) if vers == 4 else self._read_fileng(16)
ip_l = 4 if vers == 4 else 16
pt_l = size - 1 - ip_l
port = self._read_unpack(2) if pt_l else None
data = dict(
kind=kind,
length=size + 1,
subtype='ADD_ADDR',
addaddr=dict(
ipver=vers,
addrid=adid,
addr=ipaddress.ip_address(ipad),
port=port,
),
)
return data | def _read_mptcp_add(self, bits, size, kind) | Read Add Address option.
Positional arguments:
* bits - str, 4-bit data
* size - int, length of option
* kind - int, 30 (Multipath TCP)
Returns:
* dict -- extracted Add Address (ADD_ADDR) option
Structure of ADD_ADDR [RFC 6824]:
1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+---------------+---------------+-------+-------+---------------+
| Kind | Length |Subtype| IPVer | Address ID |
+---------------+---------------+-------+-------+---------------+
| Address (IPv4 - 4 octets / IPv6 - 16 octets) |
+-------------------------------+-------------------------------+
| Port (2 octets, optional) |
+-------------------------------+
Octets Bits Name Description
0 0 tcp.mp.kind Kind (30)
1 8 tcp.mp.length Length
2 16 tcp.mp.subtype Subtype (3)
2 20 tcp.mp.addaddr.ipver IP Version
3 24 tcp.mp.addaddr.addrid Address ID
4 32 tcp.mp.addaddr.addr IP Address (4/16)
8-20 64-160 tcp.mp.addaddr.port Port (optional) | 5.202873 | 3.489494 | 1.491011 |
adid = []
for _ in size:
adid.append(self._read_unpack(1))
data = dict(
subtype='REMOVE_ADDR',
removeaddr=dict(
addrid=adid or None,
),
)
return data | def _read_mptcp_remove(self, bits, size) | Read Remove Address option.
Positional arguments:
* bits - str, 4-bit data
* size - int, length of option
Returns:
* dict -- extracted Remove Address (REMOVE_ADDR) option
Structure of REMOVE_ADDR [RFC 6824]:
1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+---------------+---------------+-------+-------+---------------+
| Kind | Length = 3+n |Subtype|(resvd)| Address ID | ...
+---------------+---------------+-------+-------+---------------+
(followed by n-1 Address IDs, if required)
Octets Bits Name Description
0 0 tcp.opt.kind Kind (30)
1 8 tcp.opt.length Length
2 16 tcp.opt.mp.subtype Subtype (4)
2 20 - Reserved (must be zero)
3 24 tcp.opt.mp.removeaddr.addrid Address ID (optional list) | 9.528572 | 6.707854 | 1.42051 |
temp = self._read_unpack(1) if size else None
data = dict(
subtype='MP_PRIO',
prio=dict(
res=b'\x00' * 3,
backup=True if int(bits[3]) else False,
addrid=temp,
),
)
return data | def _read_mptcp_prio(self, bits, size) | Read Change Subflow Priority option.
Positional arguments:
* bits - str, 4-bit data
* size - int, length of option
Returns:
* dict -- extracted Change Subflow Priority (MP_PRIO) option
Structure of MP_PRIO [RFC 6824]:
1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+---------------+---------------+-------+-----+-+--------------+
| Kind | Length |Subtype| |B| AddrID (opt) |
+---------------+---------------+-------+-----+-+--------------+
Octets Bits Name Description
0 0 tcp.opt.kind Kind (30)
1 8 tcp.opt.length Length (3/4)
2 16 tcp.opt.mp.subtype Subtype (5)
2 23 tcp.opt.mp.prio.backup Backup Path (B)
3 24 tcp.opt.mp.prio.addrid Address ID (optional) | 10.681952 | 8.06461 | 1.324546 |
____ = self._read_fileng(1)
dsn_ = self._read_unpack(8)
data = dict(
subtype='MP_FAIL',
fail=dict(
dsn=dsn_,
),
)
return data | def _read_mptcp_fail(self, bits, size) | Read Fallback option.
Positional arguments:
* bits - str, 4-bit data
* size - int, length of option
Returns:
* dict -- extracted Fallback (MP_FAIL) option
Structure of MP_FAIL [RFC 6824]:
1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+---------------+---------------+-------+----------------------+
| Kind | Length=12 |Subtype| (reserved) |
+---------------+---------------+-------+----------------------+
| |
| Data Sequence Number (8 octets) |
| |
+--------------------------------------------------------------+
Octets Bits Name Description
0 0 tcp.opt.kind Kind (30)
1 8 tcp.opt.length Length (12)
2 16 tcp.opt.mp.subtype Subtype (6)
2 23 - Reserved (must be zero)
4 32 tcp.opt.mp.fail.dsn Data Sequence Number | 12.952744 | 9.346292 | 1.38587 |
____ = self._read_fileng(1)
rkey = self._read_fileng(8)
data = dict(
subtype='MP_FASTCLOSE',
fastclose=dict(
rkey=rkey,
),
)
return data | def _read_mptcp_fastclose(self, bits, size) | Read Fast Close option.
Positional arguments:
* bits - str, 4-bit data
* size - int, length of option
Returns:
* dict -- extracted Fast Close (MP_FASTCLOSE) option
Structure of MP_FASTCLOSE [RFC 6824]:
1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+---------------+---------------+-------+-----------------------+
| Kind | Length |Subtype| (reserved) |
+---------------+---------------+-------+-----------------------+
| Option Receiver's Key |
| (64 bits) |
| |
+---------------------------------------------------------------+
Octets Bits Name Description
0 0 tcp.opt.kind Kind (30)
1 8 tcp.opt.length Length (12)
2 16 tcp.opt.mp.subtype Subtype (7)
2 23 - Reserved (must be zero)
4 32 tcp.opt.mp.fastclose.rkey Option Receiver's Key | 9.071062 | 6.326001 | 1.433933 |
if isinstance(key, int):
return ESP_TransformSuite(key)
if key not in ESP_TransformSuite._member_map_:
extend_enum(ESP_TransformSuite, key, default)
return ESP_TransformSuite[key] | def get(key, default=-1) | Backport support for original codes. | 6.838775 | 6.260192 | 1.092422 |
if isinstance(key, int):
return ClassificationLevel(key)
if key not in ClassificationLevel._member_map_:
extend_enum(ClassificationLevel, key, default)
return ClassificationLevel[key] | def get(key, default=-1) | Backport support for original codes. | 4.65897 | 4.154204 | 1.121507 |
layer = layer.__layer__
if isinstance(protocol, type) and issubclass(protocol, Protocol):
protocol = protocol.__index__()
str_check(fin or '', fout or '', format or '',
trace_fout or '', trace_format or '',
engine or '', layer or '', *(protocol or ''))
bool_check(files, nofile, verbose, auto, extension, store,
ip, ipv4, ipv6, tcp, strict, trace)
return Extractor(fin=fin, fout=fout, format=format,
store=store, files=files, nofile=nofile,
auto=auto, verbose=verbose, extension=extension,
engine=engine, layer=layer, protocol=protocol,
ip=ip, ipv4=ipv4, ipv6=ipv6, tcp=tcp, strict=strict,
trace=trace, trace_fout=trace_fout, trace_format=trace_format,
trace_byteorder=trace_byteorder, trace_nanosecond=trace_nanosecond) | def extract(fin=None, fout=None, format=None, # basic settings
auto=True, extension=True, store=True, # internal settings
files=False, nofile=False, verbose=False, # output settings
engine=None, layer=None, protocol=None, # extraction settings
ip=False, ipv4=False, ipv6=False, tcp=False, strict=True, # reassembly settings
trace=False, trace_fout=None, trace_format=None, # trace settings
trace_byteorder=sys.byteorder, trace_nanosecond=False): # trace settings
if isinstance(layer, type) and issubclass(layer, Protocol) | Extract a PCAP file.
Keyword arguments:
* fin -- str, file name to be read; if file not exist, raise an error
* fout -- str, file name to be written
* format -- str, file format of output
<keyword> 'plist' / 'json' / 'tree' / 'html'
* auto -- bool, if automatically run till EOF (default is True)
<keyword> True / False
* extension -- bool, if check and append extensions to output file (default is True)
<keyword> True / False
* store -- bool, if store extracted packet info (default is True)
<keyword> True / False
* files -- bool, if split each frame into different files (default is False)
<keyword> True / False
* nofile -- bool, if no output file is to be dumped (default is False)
<keyword> True / False
* verbose -- bool, if print verbose output information (default is False)
<keyword> True / False
* engine -- str, extraction engine to be used
<keyword> 'default | pcapkit'
* layer -- str, extract til which layer
<keyword> 'Link' / 'Internet' / 'Transport' / 'Application'
* protocol -- str, extract til which protocol
<keyword> available protocol name
* ip -- bool, if record data for IPv4 & IPv6 reassembly (default is False)
<keyword> True / False
* ipv4 -- bool, if perform IPv4 reassembly (default is False)
<keyword> True / False
* ipv6 -- bool, if perform IPv6 reassembly (default is False)
<keyword> True / False
* tcp -- bool, if perform TCP reassembly (default is False)
<keyword> True / False
* strict -- bool, if set strict flag for reassembly (default is True)
<keyword> True / False
* trace -- bool, if trace TCP traffic flows (default is False)
<keyword> True / False
* trace_fout -- str, path name for flow tracer if necessary
* trace_format -- str, output file format of flow tracer
<keyword> 'plist' / 'json' / 'tree' / 'html' / 'pcap'
* trace_byteorder -- str, output file byte order
<keyword> 'little' / 'big'
* trace_nanosecond -- bool, output nanosecond-resolution file flag
<keyword> True / False
Returns:
* Extractor -- an Extractor object form `pcapkit.extractor` | 2.329496 | 2.653699 | 0.87783 |
if isinstance(file, bytes):
file = io.BytesIO(file)
io_check(file)
int_check(length or sys.maxsize)
return analyse2(file, length) | def analyse(file, length=None) | Analyse application layer packets.
Keyword arguments:
* file -- bytes or file-like object, packet to be analysed
* length -- int, length of the analysing packet
Returns:
* Analysis -- an Analysis object from `pcapkit.analyser` | 5.860556 | 7.191654 | 0.814911 |
if isinstance(protocol, type) and issubclass(protocol, Protocol):
protocol = protocol.__index__()
str_check(protocol)
bool_check(strict)
if protocol == 'IPv4':
return IPv4_Reassembly(strict=strict)
elif protocol == 'IPv6':
return IPv6_Reassembly(strict=strict)
elif protocol == 'TCP':
return TCP_Reassembly(strict=strict)
else:
raise FormatError(f'Unsupported reassembly protocol: {protocol}') | def reassemble(protocol, strict=False) | Reassemble fragmented datagrams.
Keyword arguments:
* protocol -- str, protocol to be reassembled
* strict -- bool, if return all datagrams (including those not implemented) when submit (default is False)
<keyword> True / False
Returns:
* [if protocol is IPv4] IPv4_Reassembly -- a Reassembly object from `pcapkit.reassembly`
* [if protocol is IPv6] IPv6_Reassembly -- a Reassembly object from `pcapkit.reassembly`
* [if protocol is TCP] TCP_Reassembly -- a Reassembly object from `pcapkit.reassembly` | 3.009725 | 2.914644 | 1.032622 |
str_check(fout or '', format or '')
return TraceFlow(fout=fout, format=format, byteorder=byteorder, nanosecond=nanosecond) | def trace(fout=None, format=None, byteorder=sys.byteorder, nanosecond=False) | Trace TCP flows.
Keyword arguments:
* fout -- str, output path
* format -- str, output format
* byteorder -- str, output file byte order
* nanosecond -- bool, output nanosecond-resolution file flag | 6.017859 | 6.400039 | 0.940285 |
if isinstance(key, int):
return TransType(key)
if key not in TransType._member_map_:
extend_enum(TransType, key, default)
return TransType[key] | def get(key, default=-1) | Backport support for original codes. | 5.371754 | 4.687888 | 1.145879 |
if length is None:
length = len(self)
_next = self._read_protos(1)
_temp = self._read_fileng(1)
_offm = self._read_binary(2)
_ipid = self._read_unpack(4)
ipv6_frag = dict(
next=_next,
length=8,
offset=int(_offm[:13], base=2),
mf=True if int(_offm[15], base=2) else False,
id=_ipid,
)
length -= ipv6_frag['length']
ipv6_frag['packet'] = self._read_packet(header=8, payload=length)
if extension:
self._protos = None
return ipv6_frag
return self._decode_next_layer(ipv6_frag, _next, length) | def read_ipv6_frag(self, length, extension) | Read Fragment Header for IPv6.
Structure of IPv6-Frag header [RFC 8200]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Next Header | Reserved | Fragment Offset |Res|M|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Identification |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 frag.next Next Header
1 8 - Reserved
2 16 frag.offset Fragment Offset
3 29 - Reserved
3 31 frag.mf More Flag
4 32 frag.id Identification | 5.251358 | 4.785701 | 1.097302 |
if isinstance(key, int):
return HI_Algorithm(key)
if key not in HI_Algorithm._member_map_:
extend_enum(HI_Algorithm, key, default)
return HI_Algorithm[key] | def get(key, default=-1) | Backport support for original codes. | 5.864199 | 5.282129 | 1.110196 |
if isinstance(key, int):
return Parameter(key)
if key not in Parameter._member_map_:
extend_enum(Parameter, key, default)
return Parameter[key] | def get(key, default=-1) | Backport support for original codes. | 6.334703 | 5.840917 | 1.084539 |
bin_ = bin(kind)[2:].zfill(8)
type_ = {
'copy': bool(int(bin_[0], base=2)),
'class': opt_class.get(int(bin_[1:3], base=2)),
'number': int(bin_[3:], base=2),
}
return type_ | def _read_opt_type(self, kind) | Read option type field.
Positional arguments:
* kind -- int, option kind value
Returns:
* dict -- extracted IPv4 option
Structure of option type field [RFC 791]:
Octets Bits Name Descriptions
0 0 ip.opt.type.copy Copied Flag (0/1)
0 1 ip.opt.type.class Option Class (0-3)
0 3 ip.opt.type.number Option Number | 4.670385 | 3.261973 | 1.431767 |
counter = 0 # length of read option list
optkind = list() # option kind list
options = dict() # dict of option data
while counter < size:
# get option kind
kind = self._read_unpack(1)
# fetch corresponding option tuple
opts = IPv4_OPT.get(kind)
if opts is None:
len_ = size - counter
counter = size
options['Unknown'] = self._read_fileng(len_)
break
# extract option
dscp = OPT_TYPE.get(kind)
desc = dscp.name
if opts[0]:
byte = self._read_unpack(1)
if byte: # check option process mode
data = process_opt[opts[2]](self, byte, kind)
else: # permission options (length is 2)
data = dict(
kind=kind, # option kind
type=self._read_opt_type(kind), # option type info
length=2, # option length
flag=True, # permission flag
)
else: # 1-bytes options
byte = 1
data = dict(
kind=kind, # option kind
type=self._read_opt_type(kind), # option type info
length=1, # option length
)
# record option data
counter += byte
if dscp in optkind:
if isinstance(options[desc], tuple):
options[desc] += (Info(data),)
else:
options[desc] = (Info(options[desc]), Info(data))
else:
optkind.append(dscp)
options[desc] = data
# break when eol triggered
if not kind:
break
# get padding
if counter < size:
len_ = size - counter
self._read_binary(len_)
return tuple(optkind), options | def _read_ipv4_options(self, size=None) | Read IPv4 option list.
Positional arguments:
* size -- int, buffer size
Returns:
* tuple -- IPv4 option list
* dict -- extracted IPv4 option | 4.976868 | 4.85779 | 1.024513 |
if size < 3:
raise ProtocolError(f'{self.alias}: [Optno {kind}] invalid format')
data = dict(
kind=kind,
type=self._read_opt_type(kind),
length=size,
data=self._read_fileng(size),
)
return data | def _read_mode_donone(self, size, kind) | Read options request no process.
Positional arguments:
* size - int, length of option
* kind - int, option kind value
Returns:
* dict -- extracted option
Structure of IPv4 options:
Octets Bits Name Description
0 0 ip.opt.kind Kind
0 0 ip.opt.type.copy Copied Flag
0 1 ip.opt.type.class Option Class
0 3 ip.opt.type.number Option Number
1 8 ip.opt.length Length
2 16 ip.opt.data Kind-specific Data | 8.148832 | 6.44046 | 1.265256 |
if size < 3:
raise ProtocolError(f'{self.alias}: [Optno {kind}] invalid format')
data = dict(
kind=kind,
type=self._read_opt_type(kind),
length=size,
data=self._read_unpack(size),
)
return data | def _read_mode_unpack(self, size, kind) | Read options request unpack process.
Positional arguments:
* size - int, length of option
* kind - int, option kind value
Returns:
* dict -- extracted option
Structure of IPv4 options:
Octets Bits Name Description
0 0 ip.opt.kind Kind
0 0 ip.opt.type.copy Copied Flag
0 1 ip.opt.type.class Option Class
0 3 ip.opt.type.number Option Number
1 8 ip.opt.length Length
2 16 ip.opt.data Kind-specific Data | 7.446871 | 6.077784 | 1.225261 |
if size < 3 or (size - 3) % 4 != 0:
raise ProtocolError(f'{self.alias}: [Optno {kind}] invalid format')
_rptr = self._read_unpack(1)
if _rptr < 4:
raise ProtocolError(f'{self.alias}: [Optno {kind}] invalid format')
data = dict(
kind=kind,
type=self._read_opt_type(kind),
length=size,
pointer=_rptr,
)
counter = 4
address = list()
endpoint = min(_rptr, size)
while counter < endpoint:
counter += 4
address.append(self._read_ipv4_addr())
data['ip'] = address or None
return data | def _read_mode_route(self, size, kind) | Read options with route data.
Positional arguments:
* size - int, length of option
* kind - int, 7/131/137 (RR/LSR/SSR)
Returns:
* dict -- extracted option with route data
Structure of these options:
* [RFC 791] Loose Source Route
+--------+--------+--------+---------//--------+
|10000011| length | pointer| route data |
+--------+--------+--------+---------//--------+
* [RFC 791] Strict Source Route
+--------+--------+--------+---------//--------+
|10001001| length | pointer| route data |
+--------+--------+--------+---------//--------+
* [RFC 791] Record Route
+--------+--------+--------+---------//--------+
|00000111| length | pointer| route data |
+--------+--------+--------+---------//--------+
Octets Bits Name Description
0 0 ip.opt.kind Kind (7/131/137)
0 0 ip.opt.type.copy Copied Flag (0)
0 1 ip.opt.type.class Option Class (0/1)
0 3 ip.opt.type.number Option Number (3/7/9)
1 8 ip.opt.length Length
2 16 ip.opt.pointer Pointer (≥4)
3 24 ip.opt.data Route Data | 4.989148 | 4.717987 | 1.057474 |
if size != 8:
raise ProtocolError(f'{self.alias}: [Optno {kind}] invalid format')
_type = self._read_opt_type(kind)
_fcrr = self._read_binary(1)
_func = int(_fcrr[:4], base=2)
_rate = int(_fcrr[4:], base=2)
_ttlv = self._read_unpack(1)
_nonr = self._read_binary(4)
_qsnn = int(_nonr[:30], base=2)
if _func != 0 and _func != 8:
raise ProtocolError(f'{self.alias}: [Optno {kind}] invalid format')
data = dict(
kind=kind,
type=_type,
length=size,
func=QS_FUNC.get(_func),
rate=40000 * (2 ** _rate) / 1000,
ttl=None if _func else _rate,
nounce=_qsnn,
)
return data | def _read_mode_qs(self, size, kind) | Read Quick Start option.
Positional arguments:
* size - int, length of option
* kind - int, 25 (QS)
Returns:
* dict -- extracted Quick Start (QS) option
Structure of Quick-Start (QS) option [RFC 4782]:
* A Quick-Start Request.
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Option | Length=8 | Func. | Rate | QS TTL |
| | | 0000 |Request| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| QS Nonce | R |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* Report of Approved Rate.
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Option | Length=8 | Func. | Rate | Not Used |
| | | 1000 | Report| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| QS Nonce | R |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 ip.qs.kind Kind (25)
0 0 ip.qs.type.copy Copied Flag (0)
0 1 ip.qs.type.class Option Class (0)
0 3 ip.qs.type.number Option Number (25)
1 8 ip.qs.length Length (8)
2 16 ip.qs.func Function (0/8)
2 20 ip.qs.rate Rate Request / Report (in Kbps)
3 24 ip.qs.ttl QS TTL / None
4 32 ip.qs.nounce QS Nounce
7 62 - Reserved (\x00\x00) | 5.037504 | 3.863711 | 1.303799 |
if size > 40 or size < 4:
raise ProtocolError(f'{self.alias}: [Optno {kind}] invalid format')
_tptr = self._read_unpack(1)
_oflg = self._read_binary(1)
_oflw = int(_oflg[:4], base=2)
_flag = int(_oflg[4:], base=2)
if _tptr < 5:
raise ProtocolError(f'{self.alias}: [Optno {kind}] invalid format')
data = dict(
kind=kind,
type=self._read_opt_type(kind),
length=size,
pointer=_tptr,
overflow=_oflw,
flag=_flag,
)
endpoint = min(_tptr, size)
if _flag == 0:
if (size - 4) % 4 != 0:
raise ProtocolError(f'{self.alias}: [Optno {kind}] invalid format')
counter = 5
timestamp = list()
while counter < endpoint:
counter += 4
time = self._read_unpack(4, lilendian=True)
timestamp.append(datetime.datetime.fromtimestamp(time))
data['timestamp'] = timestamp or None
elif _flag == 1 or _flag == 3:
if (size - 4) % 8 != 0:
raise ProtocolError(f'{self.alias}: [Optno {kind}] invalid format')
counter = 5
ipaddress = list()
timestamp = list()
while counter < endpoint:
counter += 8
ipaddress.append(self._read_ipv4_addr())
time = self._read_unpack(4, lilendian=True)
timestamp.append(datetime.datetime.fromtimestamp(time))
data['ip'] = ipaddress or None
data['timestamp'] = timestamp or None
else:
data['data'] = self._read_fileng(size - 4) or None
return data | def _read_mode_ts(self, size, kind) | Read Time Stamp option.
Positional arguments:
* size - int, length of option
* kind - int, 68 (TS)
Returns:
* dict -- extracted Time Stamp (TS) option
Structure of Timestamp (TS) option [RFC 791]:
+--------+--------+--------+--------+
|01000100| length | pointer|oflw|flg|
+--------+--------+--------+--------+
| internet address |
+--------+--------+--------+--------+
| timestamp |
+--------+--------+--------+--------+
| . |
.
.
Octets Bits Name Description
0 0 ip.ts.kind Kind (25)
0 0 ip.ts.type.copy Copied Flag (0)
0 1 ip.ts.type.class Option Class (0)
0 3 ip.ts.type.number Option Number (25)
1 8 ip.ts.length Length (≤40)
2 16 ip.ts.pointer Pointer (≥5)
3 24 ip.ts.overflow Overflow Octets
3 28 ip.ts.flag Flag
4 32 ip.ts.ip Internet Address
8 64 ip.ts.timestamp Timestamp | 2.900059 | 2.592212 | 1.118758 |
if size != 12:
raise ProtocolError(f'{self.alias}: [Optno {kind}] invalid format')
_idnm = self._read_unpack(2)
_ohcn = self._read_unpack(2)
_rhcn = self._read_unpack(2)
_ipad = self._read_ipv4_addr()
data = dict(
kind=kind,
type=self._read_opt_type(kind),
length=size,
id=_idnm,
ohc=_ohcn,
rhc=_rhcn,
ip=_ipad,
)
return data | def _read_mode_tr(self, size, kind) | Read Traceroute option.
Positional arguments:
size - int, length of option
kind - int, 82 (TR)
Returns:
* dict -- extracted Traceroute (TR) option
Structure of Traceroute (TR) option [RFC 1393][RFC 6814]:
0 8 16 24
+-+-+-+-+-+-+-+-+---------------+---------------+---------------+
|F| C | Number | Length | ID Number |
+-+-+-+-+-+-+-+-+---------------+---------------+---------------+
| Outbound Hop Count | Return Hop Count |
+---------------+---------------+---------------+---------------+
| Originator IP Address |
+---------------+---------------+---------------+---------------+
Octets Bits Name Description
0 0 ip.tr.kind Kind (82)
0 0 ip.tr.type.copy Copied Flag (0)
0 1 ip.tr.type.class Option Class (0)
0 3 ip.tr.type.number Option Number (18)
1 8 ip.tr.length Length (12)
2 16 ip.tr.id ID Number
4 32 ip.tr.ohc Outbound Hop Count
6 48 ip.tr.rhc Return Hop Count
8 64 ip.tr.ip Originator IP Address | 5.395495 | 3.575799 | 1.508892 |
if size < 3:
raise ProtocolError(f'{self.alias}: [Optno {kind}] invalid format')
_clvl = self._read_unpack(1)
data = dict(
kind=kind,
type=self._read_opt_type(kind),
length=size,
level=_CLASSIFICATION_LEVEL.get(_clvl, _clvl),
)
if size > 3:
_list = list()
for counter in range(3, size):
_flag = self._read_binary(1)
if (counter < size - 1 and not int(_flag[7], base=2)) \
or (counter == size - 1 and int(_flag[7], base=2)):
raise ProtocolError(f'{self.alias}: [Optno {kind}] invalid format')
_dict = dict()
for (index, bit) in enumerate(_flag[:5]):
_auth = _PROTECTION_AUTHORITY.get(index)
_dict[_auth] = True if int(bit, base=2) else False
_list.append(Info(_dict))
data['flags'] = tuple(_list)
return data | def _read_mode_sec(self, size, kind) | Read options with security info.
Positional arguments:
size - int, length of option
kind - int, 130 (SEC )/ 133 (ESEC)
Returns:
* dict -- extracted option with security info (E/SEC)
Structure of these options:
* [RFC 1108] Security (SEC)
+------------+------------+------------+-------------//----------+
| 10000010 | XXXXXXXX | SSSSSSSS | AAAAAAA[1] AAAAAAA0 |
| | | | [0] |
+------------+------------+------------+-------------//----------+
TYPE = 130 LENGTH CLASSIFICATION PROTECTION
LEVEL AUTHORITY
FLAGS
* [RFC 1108] Extended Security (ESEC):
+------------+------------+------------+-------//-------+
| 10000101 | 000LLLLL | AAAAAAAA | add sec info |
+------------+------------+------------+-------//-------+
TYPE = 133 LENGTH ADDITIONAL ADDITIONAL
SECURITY INFO SECURITY
FORMAT CODE INFO
Octets Bits Name Description
0 0 ip.sec.kind Kind (130)
0 0 ip.sec.type.copy Copied Flag (1)
0 1 ip.sec.type.class Option Class (0)
0 3 ip.sec.type.number Option Number (2)
1 8 ip.sec.length Length (≥3)
2 16 ip.sec.level Classification Level
3 24 ip.sec.flags Protection Authority Flags | 4.618284 | 4.186683 | 1.103089 |
if size != 4:
raise ProtocolError(f'{self.alias}: [Optno {kind}] invalid format')
_code = self._read_unpack(2)
data = dict(
kind=kind,
type=self._read_opt_type(kind),
length=size,
alert=_ROUTER_ALERT.get(_code, 'Reserved'),
code=_code,
)
return data | def _read_mode_rsralt(self, size, kind) | Read Router Alert option.
Positional arguments:
size - int, length of option
kind - int, 148 (RTRALT)
Returns:
* dict -- extracted Router Alert (RTRALT) option
Structure of Router Alert (RTRALT) option [RFC 2113]:
+--------+--------+--------+--------+
|10010100|00000100| 2 octet value |
+--------+--------+--------+--------+
Octets Bits Name Description
0 0 ip.rsralt.kind Kind (148)
0 0 ip.rsralt.type.copy Copied Flag (1)
0 1 ip.rsralt.type.class Option Class (0)
0 3 ip.rsralt.type.number Option Number (20)
1 8 ip.rsralt.length Length (4)
2 16 ip.rsralt.alert Alert
2 16 ip.rsralt.code Alert Code | 9.271261 | 6.222826 | 1.489879 |
_magn = self._read_fileng(4)
if _magn == b'\xd4\xc3\xb2\xa1':
lilendian = True
self._nsec = False
self._byte = 'little'
elif _magn == b'\xa1\xb2\xc3\xd4':
lilendian = False
self._nsec = False
self._byte = 'big'
elif _magn == b'\x4d\x3c\xb2\xa1':
lilendian = True
self._nsec = True
self._byte = 'little'
elif _magn == b'\xa1\xb2\x3c\x4d':
lilendian = False
self._nsec = True
self._byte = 'big'
else:
raise FileError(5, 'Unknown file format', self._file.name)
_vmaj = self._read_unpack(2, lilendian=lilendian)
_vmin = self._read_unpack(2, lilendian=lilendian)
_zone = self._read_unpack(4, lilendian=lilendian, signed=True)
_acts = self._read_unpack(4, lilendian=lilendian)
_slen = self._read_unpack(4, lilendian=lilendian)
_type = self._read_protos(4)
_byte = self._read_packet(24)
self._file = io.BytesIO(_byte)
header = dict(
magic_number=dict(
data=_magn,
byteorder=self._byte,
nanosecond=self._nsec,
),
version_major=_vmaj,
version_minor=_vmin,
thiszone=_zone,
sigfigs=_acts,
snaplen=_slen,
network=_type,
packet=_byte,
)
return header | def read_header(self) | Read global header of PCAP file.
Structure of global header (C):
typedef struct pcap_hdr_s {
guint32 magic_number; /* magic number */
guint16 version_major; /* major version number */
guint16 version_minor; /* minor version number */
gint32 thiszone; /* GMT to local correction */
guint32 sigfigs; /* accuracy of timestamps */
guint32 snaplen; /* max length of captured packets, in octets */
guint32 network; /* data link type */
} pcap_hdr_t; | 2.898687 | 2.534845 | 1.143536 |
_byte = self._read_unpack(4, lilendian=True)
_prot = LINKTYPE.get(_byte)
return _prot | def _read_protos(self, size) | Read next layer protocol type.
Positional arguments:
* size -- int, buffer size
Returns:
* str -- link layer protocol name | 18.71612 | 15.696155 | 1.192402 |
# _scur = self._file.tell()
_temp = self._read_unpack(4, lilendian=True, quiet=True)
if _temp is None:
raise EOFError
_tsss = _temp
_tsus = self._read_unpack(4, lilendian=True)
_ilen = self._read_unpack(4, lilendian=True)
_olen = self._read_unpack(4, lilendian=True)
if self._nsec:
_epch = _tsss + _tsus / 1000000000
else:
_epch = _tsss + _tsus / 1000000
_time = datetime.datetime.fromtimestamp(_epch)
frame = dict(
frame_info=dict(
ts_sec=_tsss,
ts_usec=_tsus,
incl_len=_ilen,
orig_len=_olen,
),
time=_time,
number=self._fnum,
time_epoch=_epch,
len=_ilen,
cap_len=_olen,
)
# load packet data
length = frame['len']
bytes_ = self._file.read(length)
# record file pointer
if self._mpkt and self._mpfp:
# print(self._fnum, 'ready')
self._mpfp.put(self._file.tell())
self._mpkt.pool += 1
# make BytesIO from frame packet data
frame['packet'] = bytes_
self._file = io.BytesIO(bytes_)
# frame['packet'] = self._read_packet(header=0, payload=length, discard=True)
return self._decode_next_layer(frame, length) | def read_frame(self) | Read each block after global header.
Structure of record/package header (C):
typedef struct pcaprec_hdr_s {
guint32 ts_sec; /* timestamp seconds */
guint32 ts_usec; /* timestamp microseconds */
guint32 incl_len; /* number of octets of packet saved in file */
guint32 orig_len; /* actual length of packet */
} pcaprec_hdr_t; | 4.758013 | 3.98676 | 1.193454 |
seek_cur = self._file.tell()
try:
next_ = self._import_next_layer(self._prot, length)
except Exception:
dict_['error'] = traceback.format_exc(limit=1).strip().split(os.linesep)[-1]
self._file.seek(seek_cur, os.SEEK_SET)
next_ = beholder(self._import_next_layer)(self, self._prot, length, error=True)
info, chain = next_.info, next_.protochain
# make next layer protocol name
layer = next_.alias.lower()
# proto = next_.__class__.__name__
# write info and protocol chain into dict
self._next = next_
self._protos = chain
dict_[layer] = info
dict_['protocols'] = self._protos.chain
return dict_ | def _decode_next_layer(self, dict_, length=None) | Decode next layer protocol.
Positional arguments:
dict_ -- dict, info buffer
proto -- str, next layer protocol name
length -- int, valid (not padding) length
Returns:
* dict -- current protocol with packet extracted | 6.17547 | 5.998305 | 1.029536 |
if proto == 1:
from pcapkit.protocols.link import Ethernet as Protocol
elif proto == 228:
from pcapkit.protocols.internet import IPv4 as Protocol
elif proto == 229:
from pcapkit.protocols.internet import IPv6 as Protocol
else:
from pcapkit.protocols.raw import Raw as Protocol
next_ = Protocol(self._file, length, error=error,
layer=self._exlayer, protocol=self._exproto)
return next_ | def _import_next_layer(self, proto, length, error=False) | Import next layer extractor.
Positional arguments:
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
Keyword arguments:
* error -- bool, if function call on error
Returns:
* bool -- flag if extraction of next layer succeeded
* Info -- info of next layer
* ProtoChain -- protocol chain of next layer
* str -- alias of next layer
Protocols:
* Ethernet (data link layer)
* IPv4 (internet layer)
* IPv6 (internet layer) | 3.989238 | 4.216916 | 0.946008 |
if isinstance(key, int):
return RegistrationFailure(key)
if key not in RegistrationFailure._member_map_:
extend_enum(RegistrationFailure, key, default)
return RegistrationFailure[key] | def get(key, default=-1) | Backport support for original codes. | 6.054811 | 5.269236 | 1.149087 |
if isinstance(key, int):
return TOS_PRE(key)
if key not in TOS_PRE._member_map_:
extend_enum(TOS_PRE, key, default)
return TOS_PRE[key] | def get(key, default=-1) | Backport support for original codes. | 6.498904 | 6.03659 | 1.076585 |
if length is None:
length = len(self)
raw = dict(
packet=self._read_fileng(length),
error=error or None,
)
return raw | def read_raw(self, length, *, error=None) | Read raw packet data. | 7.912155 | 6.705297 | 1.179986 |
if isinstance(key, int):
return NotifyMessage(key)
if key not in NotifyMessage._member_map_:
extend_enum(NotifyMessage, key, default)
return NotifyMessage[key] | def get(key, default=-1) | Backport support for original codes. | 5.86947 | 5.442376 | 1.078476 |
if not (isinstance(value, int) and 0 <= value <= 65535):
raise ValueError('%r is not a valid %s' % (value, cls.__name__))
if 2 <= value <= 6:
extend_enum(cls, 'Unassigned [%d]' % value, value)
return cls(value)
if 8 <= value <= 13:
extend_enum(cls, 'Unassigned [%d]' % value, value)
return cls(value)
if 21 <= value <= 23:
extend_enum(cls, 'Unassigned [%d]' % value, value)
return cls(value)
if 29 <= value <= 31:
extend_enum(cls, 'Unassigned [%d]' % value, value)
return cls(value)
if 33 <= value <= 39:
extend_enum(cls, 'Unassigned [%d]' % value, value)
return cls(value)
if 52 <= value <= 59:
extend_enum(cls, 'Unassigned [%d]' % value, value)
return cls(value)
if 63 <= value <= 69:
extend_enum(cls, 'Unassigned [%d]' % value, value)
return cls(value)
if 71 <= value <= 89:
extend_enum(cls, 'Unassigned [%d]' % value, value)
return cls(value)
if 91 <= value <= 99:
extend_enum(cls, 'Unassigned [%d]' % value, value)
return cls(value)
if 101 <= value <= 8191:
extend_enum(cls, 'Unassigned [%d]' % value, value)
return cls(value)
if 8192 <= value <= 16383:
# [RFC 7401]
extend_enum(cls, 'Reserved for Private Use [%d]' % value, value)
return cls(value)
if 16385 <= value <= 40959:
extend_enum(cls, 'Unassigned [%d]' % value, value)
return cls(value)
if 40960 <= value <= 65535:
# [RFC 7401]
extend_enum(cls, 'Reserved for Private Use [%d]' % value, value)
return cls(value)
super()._missing_(value) | def _missing_(cls, value) | Lookup function used when value is not found. | 1.615774 | 1.629554 | 0.991544 |
hdr_len = ipv6.__hdr_len__
for code in (0, 60, 43):
ext_hdr = ipv6.extension_hdrs.get(code)
if ext_hdr is not None:
hdr_len += ext_hdr.length
return hdr_len | def ipv6_hdr_len(ipv6) | Calculate length of headers before IPv6-Frag | 4.197482 | 4.312931 | 0.973232 |
chain = [type(packet).__name__]
payload = packet.data
while not isinstance(payload, bytes):
chain.append(type(payload).__name__)
payload = payload.data
return ':'.join(chain) | def packet2chain(packet) | Fetch DPKT packet protocol chain. | 3.221842 | 2.926384 | 1.100963 |
def wrapper(packet):
dict_ = dict()
for field in packet.__hdr_fields__:
dict_[field] = getattr(packet, field, None)
payload = packet.data
if not isinstance(payload, bytes):
dict_[type(payload).__name__] = wrapper(payload)
return dict_
return {
'timestamp': timestamp,
'packet': packet.pack(),
data_link.name: wrapper(packet),
} | def packet2dict(packet, timestamp, *, data_link) | Convert DPKT packet into dict. | 4.593914 | 4.258426 | 1.078782 |
ipv4 = getattr(packet, 'ip', None)
if ipv4 is not None:
if ipv4.df: # dismiss not fragmented packet
return False, None
data = dict(
bufid=(
ipaddress.ip_address(ipv4.src), # source IP address
ipaddress.ip_address(ipv4.dst), # destination IP address
ipv4.id, # identification
TP_PROTO.get(ipv4.p).name, # payload protocol type
),
num=count, # original packet range number
fo=ipv4.off, # fragment offset
ihl=ipv4.__hdr_len__, # internet header length
mf=bool(ipv4.mf), # more fragment flag
tl=ipv4.len, # total length, header includes
header=bytearray(ipv4.pack()[:ipv4.__hdr_len__]), # raw bytearray type header
payload=bytearray(ipv4.pack()[ipv4.__hdr_len__:]), # raw bytearray type payload
)
return True, data
return False, None | def ipv4_reassembly(packet, *, count=NotImplemented) | Make data for IPv4 reassembly. | 4.963302 | 4.793608 | 1.0354 |
ipv6 = getattr(packet, 'ip6', None)
if ipv6 is not None:
ipv6_frag = ipv6.extension_hdrs.get(44)
if ipv6_frag is None: # dismiss not fragmented packet
return False, None
hdr_len = ipv6_hdr_len(ipv6)
data = dict(
bufid=(
ipaddress.ip_address(ipv6.src), # source IP address
ipaddress.ip_address(ipv6.dst), # destination IP address
ipv6.flow, # label
TP_PROTO.get(ipv6_frag.nh).name, # next header field in IPv6 Fragment Header
),
num=count, # original packet range number
fo=ipv6_frag.nxt, # fragment offset
ihl=hdr_len, # header length, only headers before IPv6-Frag
mf=bool(ipv6_frag.m_flag), # more fragment flag
tl=len(ipv6), # total length, header includes
header=bytearray(ipv6.pack()[:hdr_len]), # raw bytearray type header before IPv6-Frag
payload=bytearray(ipv6.pack()[hdr_len+ipv6_frag:]), # raw bytearray type payload after IPv6-Frag
)
return True, data
return False, None | def ipv6_reassembly(packet, *, count=NotImplemented) | Make data for IPv6 reassembly. | 5.347534 | 5.222095 | 1.024021 |
if getattr(packet, 'ip', None):
ip = packet['ip']
elif getattr(packet, 'ip6', None):
ip = packet['ip6']
else:
return False, None
tcp = getattr(ip, 'tcp', None)
if tcp is not None:
flags = bin(tcp.flags)[2:].zfill(8)
data = dict(
bufid=(
ipaddress.ip_address(ip.src), # source IP address
ipaddress.ip_address(ip.dst), # destination IP address
tcp.sport, # source port
tcp.dport, # destination port
),
num=count, # original packet range number
ack=tcp.ack, # acknowledgement
dsn=tcp.seq, # data sequence number
rst=bool(int(flags[5])), # reset connection flag
syn=bool(int(flags[6])), # synchronise flag
fin=bool(int(flags[7])), # finish flag
payload=bytearray(tcp.pack()[tcp.__hdr_len__:]), # raw bytearray type payload
)
raw_len = len(tcp.data) # payload length, header excludes
data['first'] = tcp.seq # this sequence number
data['last'] = tcp.seq + raw_len # next (wanted) sequence number
data['len'] = raw_len # payload length, header excludes
return True, data
return False, None | def tcp_reassembly(packet, *, count=NotImplemented) | Make data for TCP reassembly. | 3.656744 | 3.575151 | 1.022822 |
if getattr(packet, 'ip', None):
ip = packet['ip']
elif getattr(packet, 'ip6', None):
ip = packet['ip6']
else:
return False, None
tcp = getattr(ip, 'tcp', None)
if tcp is not None:
flags = bin(tcp.flags)[2:].zfill(8)
data = dict(
protocol=data_link, # data link type from global header
index=count, # frame number
frame=packet2dict(packet, timestamp, data_link=data_link), # extracted packet
syn=bool(int(flags[6])), # TCP synchronise (SYN) flag
fin=bool(int(flags[7])), # TCP finish (FIN) flag
src=ipaddress.ip_address(ip.src), # source IP
dst=ipaddress.ip_address(ip.dst), # destination IP
srcport=tcp.sport, # TCP source port
dstport=tcp.dport, # TCP destination port
timestamp=timestamp, # timestamp
)
return True, data
return False, None | def tcp_traceflow(packet, timestamp, *, data_link, count=NotImplemented) | Trace packet flow for TCP. | 3.035797 | 3.008343 | 1.009126 |
if length is None:
length = len(self)
if length < 9:
raise ProtocolError(f'HTTP/2: invalid format', quiet=True)
_tlen = self._read_unpack(3)
_type = self._read_unpack(1)
_flag = self._read_binary(1)
_rsid = self._read_binary(4)
if _tlen != length:
raise ProtocolError(f'HTTP/2: [Type {_type}] invalid format', quiet=True)
if int(_rsid[0], base=2):
raise ProtocolError(f'HTTP/2: [Type {_type}] invalid format', quiet=True)
http = dict(
length=_tlen,
type=_HTTP_TYPE.get(_type),
sid=int(_rsid[1:], base=2),
packet=self._read_packet(_tlen),
)
if http['type'] is None:
raise ProtocolError(f'HTTP/2: [Type {_type}] invalid format', quiet=True)
if http['type'] in ('SETTINGS', 'PING') and http['sid'] != 0:
raise ProtocolError(f'HTTP/2: [Type {_type}] invalid format', quiet=True)
_http = _HTTP_FUNC[_type](self, _tlen, _type, _flag)
http.update(_http)
return http | def read_http(self, length) | Read Hypertext Transfer Protocol (HTTP/2).
Structure of HTTP/2 packet [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
+-+-------------+---------------+-------------------------------+
|R| Stream Identifier (31) |
+=+=============================================================+
| Frame Payload (0...) ...
+---------------------------------------------------------------+
Octets Bits Name Description
0 0 http.length Length
3 24 http.type Type
4 32 http.flags Flags
5 40 - Reserved
5 41 http.sid Stream Identifier
9 72 http.payload Frame Payload | 3.031287 | 2.972972 | 1.019615 |
if any((int(bit, base=2) for bit in flag)):
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
data = dict(
flags=None,
payload=self._read_fileng(size - 9) or None,
)
return data | def _read_http_none(self, size, kind, flag) | Read HTTP packet with unsigned type. | 11.013122 | 10.458527 | 1.053028 |
_plen = 0
_flag = dict(
END_STREAM=False, # bit 0
PADDED=False, # bit 3
)
for index, bit in enumerate(flag):
if index == 0 and bit:
_flag['END_STREAM'] = True
elif index == 3 and bit:
_flag['PADDED'] = True
_plen = self._read_unpack(1)
elif bit:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
else:
continue
if _plen > size - 10:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
if _flag['PADDED']:
_dlen = size - _plen - 1
else:
_dlen = size - _plen
if _dlen < 0:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
_data = self._read_fileng(_dlen)
padding = self._read_binary(_plen)
if any((int(bit, base=2) for bit in padding)):
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
data = dict(
flags=_flag,
data=_data,
)
if _flag['PADDED']:
data['ped_len'] = _plen
return data | def _read_http_data(self, size, kind, flag) | Read HTTP/2 DATA frames.
Structure of HTTP/2 DATA frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
+-+-------------+---------------+-------------------------------+
|R| Stream Identifier (31) |
+---------------+-----------------------------------------------+
|Pad Length? (8)|
+---------------+-----------------------------------------------+
| Data (*) ...
+---------------------------------------------------------------+
| Padding (*) ...
+---------------------------------------------------------------+
Octets Bits Name Description
0 0 http.length Length
3 24 http.type Type (0)
4 32 http.flags Flags
5 40 - Reserved
5 41 http.sid Stream Identifier
9 72 http.pad_len Pad Length (Optional)
10 80 http.data Data
? ? - Padding (Optional) | 2.989314 | 2.948784 | 1.013745 |
_plen = 0
_elen = 0
_flag = dict(
END_STREAM=False, # bit 0
END_HEADERS=False, # bit 2
PADDED=False, # bit 3
PRIORITY=False, # bit 5
)
for index, bit in enumerate(flag):
if index == 0 and bit:
_flag['END_STREAM'] = True
elif index == 2 and bit:
_flag['END_HEADERS'] = True
elif index == 3 and bit:
_flag['PADDED'] = True
_plen = self._read_unpack(1)
elif index == 5 and bit:
_flag['PRIORITY'] = True
_edep = self._read_binary(4)
_wght = self._read_unpack(1)
_elen = 5
elif bit:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
else:
continue
if _flag['PADDED']:
_dlen = size - _plen - _elen - 1
else:
_dlen = size - _plen - _elen
if _dlen < 0:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
_frag = self._read_fileng(_dlen) or None
padding = self._read_binary(_plen)
if any((int(bit, base=2) for bit in padding)):
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
data = dict(
flags=_flag,
frag=_frag,
)
if _flag['PADDED']:
data['ped_len'] = _plen
if _flag['PRIORITY']:
data['exclusive'] = True if int(_edep[0], base=2) else False
data['deps'] = int(_edep[1:], base=2)
data['weight'] = _wght + 1
return data | def _read_http_headers(self, size, kind, flag) | Read HTTP/2 HEADERS frames.
Structure of HTTP/2 HEADERS frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
+-+-------------+---------------+-------------------------------+
|R| Stream Identifier (31) |
+---------------+-----------------------------------------------+
|Pad Length? (8)|
+-+-------------+-----------------------------------------------+
|E| Stream Dependency? (31) |
+-+-------------+-----------------------------------------------+
| Weight? (8) |
+-+-------------+-----------------------------------------------+
| Header Block Fragment (*) ...
+---------------------------------------------------------------+
| Padding (*) ...
+---------------------------------------------------------------+
Octets Bits Name Description
0 0 http.length Length
3 24 http.type Type (1)
4 32 http.flags Flags
5 40 - Reserved
5 41 http.sid Stream Identifier
9 72 http.pad_len Pad Length (Optional)
10 80 http.exclusive Exclusive Flag
10 81 http.deps Stream Dependency (Optional)
14 112 http.weight Weight (Optional)
15 120 http.frag Header Block Fragment
? ? - Padding (Optional) | 2.915247 | 2.747008 | 1.061244 |
if size != 9:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
if any((int(bit, base=2) for bit in flag)):
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
_edep = self._read_binary(4)
_wght = self._read_unpack(1)
data = dict(
flags=None,
exclusive=True if int(_edep[0], base=2) else False,
deps=int(_edep[1:], base=2),
weight=_wght + 1,
)
return data | def _read_http_priority(self, size, kind, flag) | Read HTTP/2 PRIORITY frames.
Structure of HTTP/2 PRIORITY frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
+-+-------------+---------------+-------------------------------+
|R| Stream Identifier (31) |
+-+-------------------------------------------------------------+
|E| Stream Dependency (31) |
+-+-------------+-----------------------------------------------+
| Weight (8) |
+-+-------------+
Octets Bits Name Description
0 0 http.length Length
3 24 http.type Type (2)
4 32 http.flags Flags
5 40 - Reserved
5 41 http.sid Stream Identifier
9 72 http.exclusive Exclusive Flag
9 73 http.deps Stream Dependency
13 104 http.weight Weight | 5.049827 | 4.798385 | 1.052401 |
if size != 8:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
if any((int(bit, base=2) for bit in flag)):
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
_code = self._read_unpack(4)
data = dict(
flags=None,
error=_ERROR_CODE.get(_code, _code),
)
return data | def _read_http_rst_stream(self, size, kind, flag) | Read HTTP/2 RST_STREAM frames.
Structure of HTTP/2 RST_STREAM frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
+-+-------------+---------------+-------------------------------+
|R| Stream Identifier (31) |
+---------------------------------------------------------------+
| Error Code (32) |
+---------------------------------------------------------------+
Octets Bits Name Description
0 0 http.length Length
3 24 http.type Type (2)
4 32 http.flags Flags
5 40 - Reserved
5 41 http.sid Stream Identifier
9 72 http.error Error Code | 6.25097 | 5.823199 | 1.07346 |
if size % 5 != 0:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
_flag = dict(
ACK=False, # bit 0
)
for index, bit in enumerate(flag):
if index == 0 and bit:
_flag['ACK'] = True
elif bit:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
else:
continue
if _flag['ACK'] and size:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
_para = dict()
counter = 0
while counter < size:
_stid = self._read_unpack(1)
_pval = self._read_unpack(4)
_pkey = _PARA_NAME.get(_stid, 'Unsigned')
if _pkey in _para:
if isinstance(_para[_pkey], tuple):
_para[_pkey] += (_pval,)
else:
_para[_pkey] = (_para[_pkey], _pval)
else:
_para[_pkey] = _pval
data = dict(
flags=_flag,
)
data.update(_para)
return data | def _read_http_settings(self, size, kind, flag) | Read HTTP/2 SETTINGS frames.
Structure of HTTP/2 SETTINGS frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
+-+-------------+---------------+-------------------------------+
|R| Stream Identifier (31) |
+---------------------------------------------------------------+
| Identifier (16) |
+-------------------------------+-------------------------------+
| Value (32) |
+---------------------------------------------------------------+
| ...... |
Octets Bits Name Description
0 0 http.length Length
3 24 http.type Type (2)
4 32 http.flags Flags
5 40 - Reserved
5 41 http.sid Stream Identifier
9 72 http.settings Settings
9 72 http.settings.id Identifier
10 80 http.settings.value Value | 3.248635 | 3.362789 | 0.966054 |
if size < 4:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
_plen = 0
_flag = dict(
END_HEADERS=False, # bit 2
PADDED=False, # bit 3
)
for index, bit in enumerate(flag):
if index == 2 and bit:
_flag['END_HEADERS'] = True
elif index == 3 and bit:
_flag['PADDED'] = True
_plen = self._read_unpack(1)
elif bit:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
else:
continue
if _flag['PADDED']:
_dlen = size - _plen - 5
else:
_dlen = size - _plen - 4
if _dlen < 0:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
_rpid = self._read_binary(4)
_frag = self._read_fileng(_dlen) or None
if int(_rpid[0], base=2):
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
padding = self._read_binary(_plen)
if any((int(bit, base=2) for bit in padding)):
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
data = dict(
flags=_flag,
pid=int(_rpid[1:], base=2),
frag=_frag,
)
if _flag['PADDED']:
data['ped_len'] = _plen
return data | def _read_http_push_promise(self, size, kind, flag) | Read HTTP/2 PUSH_PROMISE frames.
Structure of HTTP/2 PUSH_PROMISE frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
+-+-------------+---------------+-------------------------------+
|R| Stream Identifier (31) |
+---------------+-----------------------------------------------+
|Pad Length? (8)|
+-+-------------+-----------------------------------------------+
|R| Promised Stream ID (31) |
+-+-----------------------------+-------------------------------+
| Header Block Fragment (*) ...
+---------------------------------------------------------------+
| Padding (*) ...
+---------------------------------------------------------------+
Octets Bits Name Description
0 0 http.length Length
3 24 http.type Type (1)
4 32 http.flags Flags
5 40 - Reserved
5 41 http.sid Stream Identifier
9 72 http.pad_len Pad Length (Optional)
10 80 - Reserved
10 81 http.pid Promised Stream ID
14 112 http.frag Header Block Fragment
? ? - Padding (Optional) | 2.84857 | 2.818524 | 1.01066 |
if size != 8:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
_flag = dict(
ACK=False, # bit 0
)
for index, bit in enumerate(flag):
if index == 0 and bit:
_flag['ACK'] = True
elif bit:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
else:
continue
_data = self._read_fileng(8)
data = dict(
flags=_flag,
data=_data,
)
return data | def _read_http_ping(self, size, kind, flag) | Read HTTP/2 PING frames.
Structure of HTTP/2 PING frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
+-+-------------+---------------+-------------------------------+
|R| Stream Identifier (31) |
+---------------------------------------------------------------+
| |
| Opaque Data (64) |
| |
+---------------------------------------------------------------+
Octets Bits Name Description
0 0 http.length Length
3 24 http.type Type (2)
4 32 http.flags Flags
5 40 - Reserved
5 41 http.sid Stream Identifier
9 72 http.data Opaque Data | 4.415834 | 4.412245 | 1.000814 |
_dlen = size - 8
if _dlen < 0:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
if any((int(bit, base=2) for bit in flag)):
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
_rsid = self._read_binary(4)
_code = self._read_unpack(4)
_data = self._read_fileng(_dlen) or None
if int(_rsid[0], base=2):
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
data = dict(
flags=None,
last_sid=int(_rsid[1:], base=2),
error=_ERROR_CODE.get(_code, _code),
data=_data,
)
return data | def _read_http_goaway(self, size, kind, flag) | Read HTTP/2 GOAWAY frames.
Structure of HTTP/2 GOAWAY frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
+-+-------------+---------------+-------------------------------+
|R| Stream Identifier (31) |
+-+-------------+---------------+-------------------------------+
|R| Last-Stream-ID (31) |
+-+-------------------------------------------------------------+
| Error Code (32) |
+---------------------------------------------------------------+
| Additional Debug Data (*) |
+---------------------------------------------------------------+
Octets Bits Name Description
0 0 http.length Length
3 24 http.type Type (2)
4 32 http.flags Flags
5 40 - Reserved
5 41 http.sid Stream Identifier
9 72 - Reserved
9 73 http.last_sid Last Stream ID
13 104 http.error Error Code
17 136 http.data Additional Debug Data (Optional) | 4.145393 | 3.964737 | 1.045566 |
if size != 4:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
if any((int(bit, base=2) for bit in flag)):
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
_size = self._read_binary(4)
if int(_size[0], base=2):
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
data = dict(
flags=None,
window=int(_size[1:], base=2),
)
return data | def _read_http_window_update(self, size, kind, flag) | Read HTTP/2 WINDOW_UPDATE frames.
Structure of HTTP/2 WINDOW_UPDATE frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
+-+-------------+---------------+-------------------------------+
|R| Stream Identifier (31) |
+-+-------------+---------------+-------------------------------+
|R| Window Size Increment (31) |
+-+-------------------------------------------------------------+
Octets Bits Name Description
0 0 http.length Length
3 24 http.type Type (2)
4 32 http.flags Flags
5 40 - Reserved
5 41 http.sid Stream Identifier
9 72 - Reserved
9 73 http.window Window Size Increment | 3.938935 | 4.139278 | 0.9516 |
_flag = dict(
END_HEADERS=False, # bit 2
)
for index, bit in enumerate(flag):
if index == 2 and bit:
_flag['END_HEADERS'] = True
elif bit:
raise ProtocolError(f'HTTP/2: [Type {kind}] invalid format', quiet=True)
else:
continue
_frag = self._read_fileng(size) or None
data = dict(
flags=_flag,
frag=_frag,
)
return data | def _read_http_continuation(self, size, kind, flag) | Read HTTP/2 WINDOW_UPDATE frames.
Structure of HTTP/2 WINDOW_UPDATE frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
+-+-------------+---------------+-------------------------------+
|R| Stream Identifier (31) |
+---------------------------------------------------------------+
| Header Block Fragment (*) ...
+---------------------------------------------------------------+
Octets Bits Name Description
0 0 http.length Length
3 24 http.type Type (2)
4 32 http.flags Flags
5 40 - Reserved
5 41 http.sid Stream Identifier
9 73 http.frag Header Block Fragment | 7.497866 | 7.467378 | 1.004083 |
if isinstance(key, int):
return OptionNumber(key)
if key not in OptionNumber._member_map_:
extend_enum(OptionNumber, key, default)
return OptionNumber[key] | def get(key, default=-1) | Backport support for original codes. | 6.175589 | 5.442229 | 1.134753 |
if self._exproto == 'null' and self._exlayer == 'None':
from pcapkit.protocols.raw import Raw as NextLayer
else:
from pcapkit.foundation.analysis import analyse as NextLayer
# from pcapkit.foundation.analysis import analyse as NextLayer
if length == 0:
next_ = NoPayload()
elif self._onerror:
next_ = beholder_ng(NextLayer)(self._file, length, _termination=self._sigterm)
else:
next_ = NextLayer(self._file, length, _termination=self._sigterm)
return next_ | def _import_next_layer(self, proto, length) | Import next layer extractor.
Positional arguments:
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
Returns:
* bool -- flag if extraction of next layer succeeded
* Info -- info of next layer
* ProtoChain -- protocol chain of next layer
* str -- alias of next layer | 6.633732 | 7.211515 | 0.919881 |
if isinstance(key, int):
return ProtectionAuthority(key)
if key not in ProtectionAuthority._member_map_:
extend_enum(ProtectionAuthority, key, default)
return ProtectionAuthority[key] | def get(key, default=-1) | Backport support for original codes. | 6.993734 | 6.199914 | 1.128037 |
if isinstance(key, int):
return RouterAlert(key)
if key not in RouterAlert._member_map_:
extend_enum(RouterAlert, key, default)
return RouterAlert[key] | def get(key, default=-1) | Backport support for original codes. | 6.849123 | 5.986969 | 1.144005 |
if isinstance(key, int):
return QS_Function(key)
if key not in QS_Function._member_map_:
extend_enum(QS_Function, key, default)
return QS_Function[key] | def get(key, default=-1) | Backport support for original codes. | 5.726119 | 5.413719 | 1.057705 |
flag = True
if self._exeng == 'dpkt':
flag, engine = self.import_test('dpkt', name='DPKT')
if flag:
return self._run_dpkt(engine)
elif self._exeng == 'scapy':
flag, engine = self.import_test('scapy.all', name='Scapy')
if flag:
return self._run_scapy(engine)
elif self._exeng == 'pyshark':
flag, engine = self.import_test('pyshark', name='PyShark')
if flag:
return self._run_pyshark(engine)
elif self._exeng == 'pipeline':
flag, engine = self.import_test('multiprocessing', name='Pipeline Multiprocessing')
self._flag_m = flag = bool(flag and (self._flag_a and CPU_CNT > 1))
if self._flag_m:
return self._run_pipeline(engine)
warnings.warn(f'extraction engine Pipeline Multiprocessing is not available; '
'using default engine instead', EngineWarning, stacklevel=stacklevel())
elif self._exeng == 'server':
flag, engine = self.import_test('multiprocessing', name='Server Multiprocessing')
self._flag_m = flag = bool(flag and (self._flag_a and CPU_CNT > 2))
if self._flag_m:
return self._run_server(engine)
warnings.warn(f'extraction engine Server Multiprocessing is not available; '
'using default engine instead', EngineWarning, stacklevel=stacklevel())
elif self._exeng not in ('default', 'pcapkit'):
flag = False
warnings.warn(f'unsupported extraction engine: {self._exeng}; '
'using default engine instead', EngineWarning, stacklevel=stacklevel())
# using default/pcapkit engine
self._exeng = self._exeng if flag else 'default'
self.record_header() # read PCAP global header
self.record_frames() | def run(self) | Start extraction. | 2.972876 | 2.923377 | 1.016932 |
self._gbhdr = Header(self._ifile)
self._vinfo = self._gbhdr.version
self._dlink = self._gbhdr.protocol
self._nnsec = self._gbhdr.nanosecond
if self._trace is not NotImplemented:
self._trace._endian = self._gbhdr.byteorder
self._trace._nnsecd = self._gbhdr.nanosecond
if not self._flag_q:
if self._flag_f:
ofile = self._ofile(f'{self._ofnm}/Global Header.{self._fext}')
ofile(self._gbhdr.info, name='Global Header')
self._type = ofile.kind
else:
self._ofile(self._gbhdr.info, name='Global Header')
self._type = self._ofile.kind | def record_header(self) | Read global header.
- Extract global header.
- Make Info object out of header properties.
- Append Info.
- Write plist file. | 6.289486 | 6.008272 | 1.046804 |
self._expkg = None
self._extmp = None
self._flag_e = True
self._ifile.close() | def _cleanup(self) | Cleanup after extraction & analysis. | 21.759422 | 17.185051 | 1.266183 |
if not self._flag_e and self._flag_m:
# join processes
[proc.join() for proc in self._mpprc]
if self._exeng == 'server':
self._mpsvc.join()
# restore attributes
if self._exeng == 'server':
self._frame = list(self._mpfrm)
self._reasm = list(self._mprsm)
self._trace = copy.deepcopy(self._mpkit.trace)
if self._exeng == 'pipeline':
self._frame = [self._mpkit.frames[x] for x in sorted(self._mpkit.frames)]
self._reasm = copy.deepcopy(self._mpkit.reassembly)
self._trace = copy.deepcopy(self._mpkit.trace)
# shutdown & cleanup
self._mpmng.shutdown()
[delattr(self, attr) for attr in filter(lambda s: s.startswith('_mp'), dir(self))]
self._frnum -= 2 | def _aftermathmp(self) | Aftermath for multiprocessing. | 5.427045 | 5.142561 | 1.055319 |
self._aftermathmp()
self._ifile.close()
self._flag_e = True | def _update_eof(self) | Update EOF flag. | 52.073692 | 37.5261 | 1.387666 |
if self._exeng == 'scapy':
return self._scapy_read_frame()
elif self._exeng == 'dpkt':
return self._dpkt_read_frame()
elif self._exeng == 'pyshark':
return self._pyshark_read_frame()
else:
return self._default_read_frame() | def _read_frame(self) | Headquarters for frame reader. | 2.873419 | 2.626183 | 1.094143 |
from pcapkit.toolkit.default import (ipv4_reassembly, ipv6_reassembly,
tcp_reassembly, tcp_traceflow)
# read frame header
if not self._flag_m:
frame = Frame(self._ifile, num=self._frnum+1, proto=self._dlink,
layer=self._exlyr, protocol=self._exptl, nanosecond=self._nnsec)
self._frnum += 1
# verbose output
if self._flag_v:
print(f' - Frame {self._frnum:>3d}: {frame.protochain}')
# write plist
frnum = f'Frame {self._frnum}'
if not self._flag_q:
if self._flag_f:
ofile = self._ofile(f'{self._ofnm}/{frnum}.{self._fext}')
ofile(frame.info, name=frnum)
else:
self._ofile(frame.info, name=frnum)
# record fragments
if self._ipv4:
flag, data = ipv4_reassembly(frame)
if flag:
self._reasm[0](data) # pylint: disable=E1102
if self._ipv6:
flag, data = ipv6_reassembly(frame)
if flag:
self._reasm[1](data) # pylint: disable=E1102
if self._tcp:
flag, data = tcp_reassembly(frame)
if flag:
self._reasm[2](data) # pylint: disable=E1102
# trace flows
if self._flag_t:
flag, data = tcp_traceflow(frame, data_link=self._dlink)
if flag:
self._trace(data)
# record frames
if self._exeng == 'pipeline':
if self._flag_d:
# frame._file = NotImplemented
mpkit.frames[self._frnum] = frame
# print(self._frnum, 'stored')
mpkit.current += 1
elif self._exeng == 'server':
# record frames
if self._flag_d:
# frame._file = NotImplemented
self._frame.append(frame)
# print(self._frnum, 'stored')
self._frnum += 1
else:
if self._flag_d:
self._frame.append(frame)
self._proto = frame.protochain.chain
# return frame record
return frame | def _default_read_frame(self, *, frame=None, mpkit=None) | Read frames with default engine.
- Extract frames and each layer of packets.
- Make Info object out of frame properties.
- Append Info.
- Write plist & append Info. | 3.764595 | 3.768539 | 0.998954 |
# if not self._flag_a:
# self._flag_a = True
# warnings.warn(f"'Extractor(engine=scapy)' object is not iterable; "
# "so 'auto=False' will be ignored", AttributeWarning, stacklevel=stacklevel())
if self._exlyr != 'None' or self._exptl != 'null':
warnings.warn("'Extractor(engine=scapy)' does not support protocol and layer threshold; "
f"'layer={self._exlyr}' and 'protocol={self._exptl}' ignored",
AttributeWarning, stacklevel=stacklevel())
# extract & analyse file
self._expkg = scapy_all
self._extmp = iter(scapy_all.sniff(offline=self._ifnm))
# start iteration
self.record_frames() | def _run_scapy(self, scapy_all) | Call scapy.all.sniff to extract PCAP files. | 9.224078 | 8.885402 | 1.038116 |
from pcapkit.toolkit.scapy import (ipv4_reassembly, ipv6_reassembly,
packet2chain, packet2dict, tcp_reassembly,
tcp_traceflow)
# fetch Scapy packet
packet = next(self._extmp)
# verbose output
self._frnum += 1
self._proto = packet2chain(packet)
if self._flag_v:
print(f' - Frame {self._frnum:>3d}: {self._proto}')
# write plist
frnum = f'Frame {self._frnum}'
if not self._flag_q:
info = packet2dict(packet)
if self._flag_f:
ofile = self._ofile(f'{self._ofnm}/{frnum}.{self._fext}')
ofile(info, name=frnum)
else:
self._ofile(info, name=frnum)
# record frames
if self._flag_d:
# setattr(packet, 'packet2dict', packet2dict)
# setattr(packet, 'packet2chain', packet2chain)
self._frame.append(packet)
# record fragments
if self._ipv4:
flag, data = ipv4_reassembly(packet, count=self._frnum)
if flag:
self._reasm[0](data) # pylint: disable=E1102
if self._ipv6:
flag, data = ipv6_reassembly(packet, count=self._frnum)
if flag:
self._reasm[1](data) # pylint: disable=E1102
if self._tcp:
flag, data = tcp_reassembly(packet, count=self._frnum)
if flag:
self._reasm[2](data) # pylint: disable=E1102
# trace flows
if self._flag_t:
flag, data = tcp_traceflow(packet, count=self._frnum)
if flag:
self._trace(data)
return packet | def _scapy_read_frame(self) | Read frames with Scapy. | 3.112827 | 3.061014 | 1.016927 |
# if not self._flag_a:
# self._flag_a = True
# warnings.warn(f"'Extractor(engine=dpkt)' object is not iterable; "
# "so 'auto=False' will be ignored", AttributeWarning, stacklevel=stacklevel())
if self._exlyr != 'None' or self._exptl != 'null':
warnings.warn("'Extractor(engine=dpkt)' does not support protocol and layer threshold; "
f"'layer={self._exlyr}' and 'protocol={self._exptl}' ignored",
AttributeWarning, stacklevel=stacklevel())
# extract global header
self.record_header()
self._ifile.seek(0, os.SEEK_SET)
# extract & analyse file
self._expkg = dpkt
self._extmp = iter(dpkt.pcap.Reader(self._ifile))
# start iteration
self.record_frames() | def _run_dpkt(self, dpkt) | Call dpkt.pcap.Reader to extract PCAP files. | 8.363746 | 7.834589 | 1.067541 |
from pcapkit.toolkit.dpkt import (ipv4_reassembly, ipv6_reassembly,
packet2chain, packet2dict, tcp_reassembly,
tcp_traceflow)
# fetch DPKT packet
timestamp, packet = next(self._extmp)
# extract packet
if self._dlink.value == 1:
packet = self._expkg.ethernet.Ethernet(packet)
elif self._dlink.value == 228:
packet = self._expkg.ip.IP(packet)
elif self._dlink.value == 229:
packet = self._expkg.ip6.IP6(packet)
else:
warnings.warn('unrecognised link layer protocol; all analysis functions ignored',
DPKTWarning, stacklevel=stacklevel())
self._frnum += 1
if self._flag_d:
self._frame.append(packet)
return packet
# verbose output
self._frnum += 1
self._proto = packet2chain(packet)
if self._flag_v:
print(f' - Frame {self._frnum:>3d}: {self._proto}')
# write plist
frnum = f'Frame {self._frnum}'
if not self._flag_q:
info = packet2dict(packet, timestamp, data_link=self._dlink)
if self._flag_f:
ofile = self._ofile(f'{self._ofnm}/{frnum}.{self._fext}')
ofile(info, name=frnum)
else:
self._ofile(info, name=frnum)
# record frames
if self._flag_d:
setattr(packet, 'packet2dict', packet2dict)
setattr(packet, 'packet2chain', packet2chain)
self._frame.append(packet)
# record fragments
if self._ipv4:
flag, data = ipv4_reassembly(packet, count=self._frnum)
if flag:
self._reasm[0](data) # pylint: disable=E1102
if self._ipv6:
flag, data = ipv6_reassembly(packet, count=self._frnum)
if flag:
self._reasm[1](data) # pylint: disable=E1102
if self._tcp:
flag, data = tcp_reassembly(packet, count=self._frnum)
if flag:
self._reasm[2](data) # pylint: disable=E1102
# trace flows
if self._flag_t:
flag, data = tcp_traceflow(packet, timestamp, data_link=self._dlink, count=self._frnum)
if flag:
self._trace(data)
return packet | def _dpkt_read_frame(self) | Read frames. | 3.339005 | 3.306936 | 1.009697 |
# if not self._flag_a:
# self._flag_a = True
# warnings.warn(f"'Extractor(engine=pyshark)' object is not iterable; "
# "so 'auto=False' will be ignored", AttributeWarning, stacklevel=stacklevel())
if self._exlyr != 'None' or self._exptl != 'null':
warnings.warn("'Extractor(engine=pyshark)' does not support protocol and layer threshold; "
f"'layer={self._exlyr}' and 'protocol={self._exptl}' ignored",
AttributeWarning, stacklevel=stacklevel())
if (self._ipv4 or self._ipv6 or self._tcp):
self._ipv4 = self._ipv6 = self._tcp = False
self._reasm = [None] * 3
warnings.warn("'Extractor(engine=pyshark)' object dose not support reassembly; "
f"so 'ipv4={self._ipv4}', 'ipv6={self._ipv6}' and 'tcp={self._tcp}' will be ignored",
AttributeWarning, stacklevel=stacklevel())
# extract & analyse file
self._expkg = pyshark
self._extmp = iter(pyshark.FileCapture(self._ifnm, keep_packets=False))
# start iteration
self.record_frames() | def _run_pyshark(self, pyshark) | Call pyshark.FileCapture to extract PCAP files. | 5.656137 | 5.50624 | 1.027223 |
from pcapkit.toolkit.pyshark import packet2dict, tcp_traceflow
# fetch PyShark packet
packet = next(self._extmp)
# def _pyshark_packet2chain(packet):
#
# return ':'.join(map(lambda layer: layer.layer_name.upper(), packet.layers))
# verbose output
self._frnum = int(packet.number)
self._proto = packet.frame_info.protocols
if self._flag_v:
print(f' - Frame {self._frnum:>3d}: {self._proto}')
# write plist
frnum = f'Frame {self._frnum}'
if not self._flag_q:
info = packet2dict(packet)
if self._flag_f:
ofile = self._ofile(f'{self._ofnm}/{frnum}.{self._fext}')
ofile(info, name=frnum)
else:
self._ofile(info, name=frnum)
# record frames
if self._flag_d:
setattr(packet, 'packet2dict', packet2dict)
self._frame.append(packet)
# trace flows
if self._flag_t:
flag, data = tcp_traceflow(packet)
if flag:
self._trace(data)
return packet | def _pyshark_read_frame(self) | Read frames. | 5.507267 | 5.430785 | 1.014083 |
if not self._flag_m:
raise UnsupportedCall(f"Extractor(engine={self._exeng})' has no attribute '_run_pipline'")
if not self._flag_q:
self._flag_q = True
warnings.warn("'Extractor(engine=pipeline)' does not support output; "
f"'fout={self._ofnm}' ignored", AttributeWarning, stacklevel=stacklevel())
self._frnum = 1 # frame number (revised)
self._expkg = multiprocessing # multiprocessing module
self._mpprc = list() # multiprocessing process list
self._mpfdp = collections.defaultdict(multiprocessing.Queue) # multiprocessing file pointer
self._mpmng = multiprocessing.Manager() # multiprocessing manager
self._mpkit = self._mpmng.Namespace() # multiprocessing work kit
self._mpkit.counter = 0 # work count (on duty)
self._mpkit.pool = 1 # work pool (ready)
self._mpkit.current = 1 # current frame number
self._mpkit.eof = False # EOF flag
self._mpkit.frames = dict() # frame storage
self._mpkit.trace = self._trace # flow tracer
self._mpkit.reassembly = copy.deepcopy(self._reasm) # reassembly buffers
# preparation
self.record_header()
self._mpfdp[0].put(self._gbhdr.length)
# extraction
while True:
# check EOF
if self._mpkit.eof:
self._update_eof()
break
# check counter
if self._mpkit.pool and self._mpkit.counter < CPU_CNT:
# update file offset
self._ifile.seek(self._mpfdp.pop(self._frnum-1).get(), os.SEEK_SET)
# create worker
# print(self._frnum, 'start')
proc = multiprocessing.Process(
target=self._pipeline_read_frame,
kwargs={'mpkit': self._mpkit, 'mpfdp': self._mpfdp[self._frnum]}
)
# update status
self._mpkit.pool -= 1
self._mpkit.counter += 1
# start and record
proc.start()
self._frnum += 1
self._mpprc.append(proc)
# check buffer
if len(self._mpprc) >= CPU_CNT:
[proc.join() for proc in self._mpprc[:-4]]
del self._mpprc[:-4] | def _run_pipeline(self, multiprocessing) | Use pipeline multiprocessing to extract PCAP files. | 5.348894 | 5.18903 | 1.030808 |
# check EOF
if self._flag_e:
raise EOFError
def _analyse_frame(*, frame, mpkit):
# wait until ready
while mpkit.current != self._frnum:
time.sleep(random.randint(0, datetime.datetime.now().second) // 600)
# analysis and storage
# print(self._frnum, 'get')
self._trace = mpkit.trace
self._reasm = mpkit.reassembly
self._default_read_frame(frame=frame, mpkit=mpkit)
# print(self._frnum, 'analysed')
mpkit.trace = copy.deepcopy(self._trace)
mpkit.reassembly = copy.deepcopy(self._reasm)
# print(self._frnum, 'put')
# extract frame
try:
# extraction
frame = Frame(self._ifile, num=self._frnum, proto=self._dlink, layer=self._exlyr,
protocol=self._exptl, nanosecond=self._nnsec, mpkit=mpkit, mpfdp=mpfdp)
# analysis
_analyse_frame(frame=frame, mpkit=mpkit)
except EOFError:
mpkit.eof = True
finally:
mpkit.counter -= 1
self._ifile.close() | def _pipeline_read_frame(self, *, mpfdp, mpkit) | Extract frame. | 5.354683 | 5.215911 | 1.026606 |
if not self._flag_m:
raise UnsupportedCall(f"Extractor(engine={self._exeng})' has no attribute '_run_server'")
if not self._flag_q:
self._flag_q = True
warnings.warn("'Extractor(engine=pipeline)' does not support output; "
f"'fout={self._ofnm}' ignored", AttributeWarning, stacklevel=stacklevel())
self._frnum = 1 # frame number (revised)
self._expkg = multiprocessing # multiprocessing module
self._mpsvc = NotImplemented # multiprocessing server process
self._mpprc = list() # multiprocessing process list
self._mpfdp = collections.defaultdict(multiprocessing.Queue) # multiprocessing file pointer
self._mpmng = multiprocessing.Manager() # multiprocessing manager
self._mpbuf = self._mpmng.dict() # multiprocessing frame dict
self._mpfrm = self._mpmng.list() # multiprocessing frame storage
self._mprsm = self._mpmng.list() # multiprocessing reassembly buffer
self._mpkit = self._mpmng.Namespace() # multiprocessing work kit
self._mpkit.counter = 0 # work count (on duty)
self._mpkit.pool = 1 # work pool (ready)
self._mpkit.eof = False # EOF flag
self._mpkit.trace = None # flow tracer
# preparation
self.record_header()
self._mpfdp[0].put(self._gbhdr.length)
self._mpsvc = multiprocessing.Process(
target=self._server_analyse_frame,
kwargs={'mpfrm': self._mpfrm, 'mprsm': self._mprsm, 'mpbuf': self._mpbuf, 'mpkit': self._mpkit}
)
self._mpsvc.start()
# extraction
while True:
# check EOF
if self._mpkit.eof:
self._update_eof()
break
# check counter
if self._mpkit.pool and self._mpkit.counter < CPU_CNT - 1:
# update file offset
self._ifile.seek(self._mpfdp.pop(self._frnum-1).get(), os.SEEK_SET)
# create worker
# print(self._frnum, 'start')
proc = multiprocessing.Process(
target=self._server_extract_frame,
kwargs={'mpkit': self._mpkit, 'mpbuf': self._mpbuf, 'mpfdp': self._mpfdp[self._frnum]}
)
# update status
self._mpkit.pool -= 1
self._mpkit.counter += 1
# start and record
proc.start()
self._frnum += 1
self._mpprc.append(proc)
# check buffer
if len(self._mpprc) >= CPU_CNT - 1:
[proc.join() for proc in self._mpprc[:-4]]
del self._mpprc[:-4] | def _run_server(self, multiprocessing) | Use server multiprocessing to extract PCAP files. | 4.696997 | 4.557739 | 1.030554 |
# check EOF
if self._flag_e:
raise EOFError
# extract frame
try:
frame = Frame(self._ifile, num=self._frnum, proto=self._dlink, layer=self._exlyr,
protocol=self._exptl, nanosecond=self._nnsec, mpkit=mpkit, mpfdp=mpfdp)
# frame._file = NotImplemented
mpbuf[self._frnum] = frame
except EOFError:
mpbuf[self._frnum] = EOFError
mpkit.eof = True
finally:
mpkit.counter -= 1
self._ifile.close() | def _server_extract_frame(self, *, mpfdp, mpkit, mpbuf) | Extract frame. | 7.591558 | 7.337444 | 1.034633 |
while True:
# fetch frame
# print(self._frnum, 'trying')
frame = mpbuf.pop(self._frnum, None)
if frame is EOFError:
break
if frame is None:
continue
# print(self._frnum, 'get')
self._default_read_frame(frame=frame)
mpfrm += self._frame
mprsm += self._reasm
mpkit.trace = copy.deepcopy(self._trace) | def _server_analyse_frame(self, *, mpkit, mpfrm, mprsm, mpbuf) | Analyse frame. | 7.207861 | 6.945131 | 1.037829 |
if isinstance(key, int):
return Checksum(key)
if key not in Checksum._member_map_:
extend_enum(Checksum, key, default)
return Checksum[key] | def get(key, default=-1) | Backport support for original codes. | 5.865596 | 5.381733 | 1.089908 |
if isinstance(key, int):
return Operation(key)
if key not in Operation._member_map_:
extend_enum(Operation, key, default)
return Operation[key] | def get(key, default=-1) | Backport support for original codes. | 5.437543 | 4.820097 | 1.128098 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.