_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q1200
HIP._read_para_reg_from
train
def _read_para_reg_from(self, code, cbit, clen, *, desc, length, version): """Read HIP REG_FROM parameter. Structure of HIP REG_FROM parameter [RFC 5770]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Port | Protocol | Reserved | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Address | | | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 reg_from.type Parameter Type 1 15 reg_from.critical Critical Bit 2 16 reg_from.length Length of Contents 4 32 reg_from.port Port 6 48 reg_from.protocol Protocol 7 56 - Reserved 8 64 reg_from.ip Address (IPv6) """ if clen != 20: raise ProtocolError(f'HIPv{version}: [Parano {code}] invalid format') _port = self._read_unpack(2) _ptcl = self._read_unpack(1) _resv = self._read_fileng(1) _addr = self._read_fileng(16) reg_from = dict( type=desc, critical=cbit, length=clen, port=_port, protocol=TP_PROTO.get(_ptcl), ip=ipaddress.ip_address(_addr), ) return reg_from
python
{ "resource": "" }
q1201
HIP._read_para_echo_response_signed
train
def _read_para_echo_response_signed(self, code, cbit, clen, *, desc, length, version): """Read HIP ECHO_RESPONSE_SIGNED parameter. Structure of HIP ECHO_RESPONSE_SIGNED parameter [RFC 7401]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Opaque data (variable length) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 echo_response_signed.type Parameter Type 1 15 echo_response_signed.critical Critical Bit 2 16 echo_response_signed.length Length of Contents 4 32 echo_response_signed.data Opaque Data """ _data = self._read_fileng(clen) echo_response_signed = dict( type=desc, critical=cbit, length=clen, data=_data, ) _plen = length - clen if _plen: self._read_fileng(_plen) return echo_response_signed
python
{ "resource": "" }
q1202
HIP._read_para_transport_format_list
train
def _read_para_transport_format_list(self, code, cbit, clen, *, desc, length, version): """Read HIP TRANSPORT_FORMAT_LIST parameter. Structure of HIP TRANSPORT_FORMAT_LIST parameter [RFC 7401]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | TF type #1 | TF type #2 / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / TF type #n | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 transport_format_list.type Parameter Type 1 15 transport_format_list.critical Critical Bit 2 16 transport_format_list.length Length of Contents 4 32 transport_format_list.tf_type TF Type ............ ? ? - Padding """ if clen % 2 != 0: raise ProtocolError(f'HIPv{version}: [Parano {code}] invalid format') _tfid = list() for _ in range(clen // 2): _tfid.append(self._read_unpack(2)) transport_format_list = dict( type=desc, critical=cbit, length=clen, tf_type=tuple(_tfid), ) _plen = length - clen if _plen: self._read_fileng(_plen) return transport_format_list
python
{ "resource": "" }
q1203
HIP._read_para_esp_transform
train
def _read_para_esp_transform(self, code, cbit, clen, *, desc, length, version): """Read HIP ESP_TRANSFORM parameter. Structure of HIP ESP_TRANSFORM parameter [RFC 7402]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Reserved | Suite ID #1 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Suite ID #2 | Suite ID #3 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Suite ID #n | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 esp_transform.type Parameter Type 1 15 esp_transform.critical Critical Bit 2 16 esp_transform.length Length of Contents 4 32 - Reserved 6 48 esp_transform.id Suite ID ............ ? ? - Padding """ if clen % 2 != 0: raise ProtocolError(f'HIPv{version}: [Parano {code}] invalid format') _resv = self._read_fileng(2) _stid = list() for _ in range((clen - 2) // 2): _stid.append(_ESP_SUITE_ID.get(self._read_unpack(2), 'Unassigned')) esp_transform = dict( type=desc, critical=cbit, length=clen, id=tuple(_stid), ) _plen = length - clen if _plen: self._read_fileng(_plen) return esp_transform
python
{ "resource": "" }
q1204
HIP._read_para_seq_data
train
def _read_para_seq_data(self, code, cbit, clen, *, desc, length, version): """Read HIP SEQ_DATA parameter. Structure of HIP SEQ_DATA parameter [RFC 6078]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Sequence number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 seq_data.type Parameter Type 1 15 seq_data.critical Critical Bit 2 16 seq_data.length Length of Contents 4 32 seq_data.seq Sequence number """ if clen != 4: raise ProtocolError(f'HIPv{version}: [Parano {code}] invalid format') _seqn = self._read_unpack(4) seq_data = dict( type=desc, critical=cbit, length=clen, seq=_seqn, ) return seq_data
python
{ "resource": "" }
q1205
HIP._read_para_route_dst
train
def _read_para_route_dst(self, code, cbit, clen, *, desc, length, version): """Read HIP ROUTE_DST parameter. Structure of HIP ROUTE_DST parameter [RFC 6028]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Flags | Reserved | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | HIT #1 | | | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . . . . . . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | HIT #n | | | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 route_dst.type Parameter Type 1 15 route_dst.critical Critical Bit 2 16 route_dst.length Length of Contents 4 32 route_dst.flags Flags 4 32 route_dst.flags.symmetric SYMMETRIC [RFC 6028] 4 33 route_dst.flags.must_follow MUST_FOLLOW [RFC 6028] 6 48 - Reserved 8 64 route_dst.ip HIT ............ """ if (clen - 4) % 16 != 0: raise ProtocolError(f'HIPv{version}: [Parano {code}] invalid format') _flag = self._read_binary(2) _resv = self._read_fileng(2) _addr = list() for _ in range((clen - 4) // 16): _addr.append(ipaddress.ip_address(self._read_fileng(16))) route_dst = dict( type=desc, critical=cbit, length=clen, flags=dict( symmetric=True if int(_flag[0], base=2) else False, must_follow=True if int(_flag[1], base=2) else False, ), ip=tuple(_addr), ) return route_dst
python
{ "resource": "" }
q1206
HIP._read_para_hip_transport_mode
train
def _read_para_hip_transport_mode(self, code, cbit, clen, *, desc, length, version): """Read HIP HIP_TRANSPORT_MODE parameter. Structure of HIP HIP_TRANSPORT_MODE parameter [RFC 6261]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Port | Mode ID #1 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Mode ID #2 | Mode ID #3 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Mode ID #n | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hip_transport_mode.type Parameter Type 1 15 hip_transport_mode.critical Critical Bit 2 16 hip_transport_mode.length Length of Contents 4 32 hip_transport_mode.port Port 6 48 hip_transport_mode.id Mode ID ............ ? ? - Padding """ if clen % 2 != 0: raise ProtocolError(f'HIPv{version}: [Parano {code}] invalid format') _port = self._read_unpack(2) _mdid = list() for _ in range((clen - 2) // 2): _mdid.append(_TP_MODE_ID.get(self._read_unpack(2), 'Unassigned')) hip_transport_mode = dict( type=desc, critical=cbit, length=clen, port=_port, id=tuple(_mdid), ) _plen = length - clen if _plen: self._read_fileng(_plen) return hip_transport_mode
python
{ "resource": "" }
q1207
HIP._read_para_hip_mac
train
def _read_para_hip_mac(self, code, cbit, clen, *, desc, length, version): """Read HIP HIP_MAC parameter. Structure of HIP HIP_MAC parameter [RFC 7401]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | HMAC | / / / +-------------------------------+ | | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hip_mac.type Parameter Type 1 15 hip_mac.critical Critical Bit 2 16 hip_mac.length Length of Contents 4 32 hip_mac.hmac HMAC ? ? - Padding """ _hmac = self._read_fileng(clen) hip_mac = dict( type=desc, critical=cbit, length=clen, hmac=_hmac, ) _plen = length - clen if _plen: self._read_fileng(_plen) return hip_mac
python
{ "resource": "" }
q1208
HIP._read_para_hip_mac_2
train
def _read_para_hip_mac_2(self, code, cbit, clen, *, desc, length, version): """Read HIP HIP_MAC_2 parameter. Structure of HIP HIP_MAC_2 parameter [RFC 7401]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | HMAC | / / / +-------------------------------+ | | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hip_mac_2.type Parameter Type 1 15 hip_mac_2.critical Critical Bit 2 16 hip_mac_2.length Length of Contents 4 32 hip_mac_2.hmac HMAC ? ? - Padding """ _hmac = self._read_fileng(clen) hip_mac_2 = dict( type=desc, critical=cbit, length=clen, hmac=_hmac, ) _plen = length - clen if _plen: self._read_fileng(_plen) return hip_mac_2
python
{ "resource": "" }
q1209
HIP._read_para_hip_signature_2
train
def _read_para_hip_signature_2(self, code, cbit, clen, *, desc, length, version): """Read HIP HIP_SIGNATURE_2 parameter. Structure of HIP HIP_SIGNATURE_2 parameter [RFC 7401]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | SIG alg | Signature / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hip_signature_2.type Parameter Type 1 15 hip_signature_2.critical Critical Bit 2 16 hip_signature_2.length Length of Contents 4 32 hip_signature_2.algorithm SIG Algorithm 6 48 hip_signature_2.signature Signature ? ? - Padding """ _algo = self._read_unpack(2) _sign = self._read_fileng(clen-2) hip_signature_2 = dict( type=desc, critical=cbit, length=clen, algorithm=_HI_ALGORITHM.get(_algo, 'Unassigned'), signature=_sign, ) _plen = length - clen if _plen: self._read_fileng(_plen) return hip_signature_2
python
{ "resource": "" }
q1210
HIP._read_para_echo_request_unsigned
train
def _read_para_echo_request_unsigned(self, code, cbit, clen, *, desc, length, version): """Read HIP ECHO_REQUEST_UNSIGNED parameter. Structure of HIP ECHO_REQUEST_UNSIGNED parameter [RFC 7401]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Opaque data (variable length) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 echo_request_unsigned.type Parameter Type 1 15 echo_request_unsigned.critical Critical Bit 2 16 echo_request_unsigned.length Length of Contents 4 32 echo_request_unsigned.data Opaque Data """ _data = self._read_fileng(clen) echo_request_unsigned = dict( type=desc, critical=cbit, length=clen, data=_data, ) _plen = length - clen if _plen: self._read_fileng(_plen) return echo_request_unsigned
python
{ "resource": "" }
q1211
HIP._read_para_echo_response_unsigned
train
def _read_para_echo_response_unsigned(self, code, cbit, clen, *, desc, length, version): """Read HIP ECHO_RESPONSE_UNSIGNED parameter. Structure of HIP ECHO_RESPONSE_UNSIGNED parameter [RFC 7401]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Opaque data (variable length) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 echo_response_unsigned.type Parameter Type 1 15 echo_response_unsigned.critical Critical Bit 2 16 echo_response_unsigned.length Length of Contents 4 32 echo_response_unsigned.data Opaque Data """ _data = self._read_fileng(clen) echo_response_unsigned = dict( type=desc, critical=cbit, length=clen, data=_data, ) _plen = length - clen if _plen: self._read_fileng(_plen) return echo_response_unsigned
python
{ "resource": "" }
q1212
HIP._read_para_overlay_ttl
train
def _read_para_overlay_ttl(self, code, cbit, clen, *, desc, length, version): """Read HIP OVERLAY_TTL parameter. Structure of HIP OVERLAY_TTL parameter [RFC 6078]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | TTL | Reserved | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 overlay_ttl.type Parameter Type 1 15 overlay_ttl.critical Critical Bit 2 16 overlay_ttl.length Length of Contents 4 32 overlay_ttl.ttl TTL 6 48 - Reserved """ if clen != 4: raise ProtocolError(f'HIPv{version}: [Parano {code}] invalid format') _ttln = self._read_unpack(2) overlay_ttl = dict( type=desc, critical=cbit, length=clen, ttl=_ttln, ) return overlay_ttl
python
{ "resource": "" }
q1213
HIP._read_para_from
train
def _read_para_from(self, code, cbit, clen, *, desc, length, version): """Read HIP FROM parameter. Structure of HIP FROM parameter [RFC 8004]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Address | | | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 from.type Parameter Type 1 15 from.critical Critical Bit 2 16 from.length Length of Contents 4 32 from.ip Address """ if clen != 16: raise ProtocolError(f'HIPv{version}: [Parano {code}] invalid format') _addr = self._read_fileng(16) from_ = dict( type=desc, critical=cbit, length=clen, ip=ipaddress.ip_address(_addr), ) return from_
python
{ "resource": "" }
q1214
HIP._read_para_rvs_hmac
train
def _read_para_rvs_hmac(self, code, cbit, clen, *, desc, length, version): """Read HIP RVS_HMAC parameter. Structure of HIP RVS_HMAC parameter [RFC 8004]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | HMAC | / / / +-------------------------------+ | | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 rvs_hmac.type Parameter Type 1 15 rvs_hmac.critical Critical Bit 2 16 rvs_hmac.length Length of Contents 4 32 rvs_hmac.hmac HMAC ? ? - Padding """ _hmac = self._read_fileng(clen) rvs_hmac = dict( type=desc, critical=cbit, length=clen, hmac=_hmac, ) _plen = length - clen if _plen: self._read_fileng(_plen) return rvs_hmac
python
{ "resource": "" }
q1215
HIP._read_para_via_rvs
train
def _read_para_via_rvs(self, code, cbit, clen, *, desc, length, version): """Read HIP VIA_RVS parameter. Structure of HIP VIA_RVS parameter [RFC 6028]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type | Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Address | | | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ . . . . . . +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Address | | | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 via_rvs.type Parameter Type 1 15 via_rvs.critical Critical Bit 2 16 via_rvs.length Length of Contents 4 32 via_rvs.ip Address ............ """ if clen % 16 != 0: raise ProtocolError(f'HIPv{version}: [Parano {code}] invalid format') _addr = list() for _ in range(clen // 16): _addr.append(ipaddress.ip_address(self._read_fileng(16))) via_rvs = dict( type=desc, critical=cbit, length=clen, ip=tuple(_addr), ) return via_rvs
python
{ "resource": "" }
q1216
HIP._read_para_relay_hmac
train
def _read_para_relay_hmac(self, code, cbit, clen, *, desc, length, version): """Read HIP RELAY_HMAC parameter. Structure of HIP RELAY_HMAC parameter [RFC 5770]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | HMAC | / / / +-------------------------------+ | | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 relay_hmac.type Parameter Type 1 15 relay_hmac.critical Critical Bit 2 16 relay_hmac.length Length of Contents 4 32 relay_hmac.hmac HMAC ? ? - Padding """ _hmac = self._read_fileng(clen) relay_hmac = dict( type=desc, critical=cbit, length=clen, hmac=_hmac, ) _plen = length - clen if _plen: self._read_fileng(_plen) return relay_hmac
python
{ "resource": "" }
q1217
stacklevel
train
def stacklevel(): """Fetch current stack level.""" pcapkit = f'{os.path.sep}pcapkit{os.path.sep}' tb = traceback.extract_stack() for index, tbitem in enumerate(tb): if pcapkit in tbitem[0]: break else: index = len(tb) return (index-1)
python
{ "resource": "" }
q1218
seekset_ng
train
def seekset_ng(func): """Read file from start then set back to original.""" @functools.wraps(func) def seekcur(file, *args, seekset=os.SEEK_SET, **kw): # seek_cur = file.tell() file.seek(seekset, os.SEEK_SET) return_ = func(file, *args, seekset=seekset, **kw) # file.seek(seek_cur, os.SEEK_SET) return return_ return seekcur
python
{ "resource": "" }
q1219
beholder_ng
train
def beholder_ng(func): """Behold analysis procedure.""" @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
python
{ "resource": "" }
q1220
L2TP.read_l2tp
train
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) """ 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)
python
{ "resource": "" }
q1221
VLAN.read_vlan
train
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) """ 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)
python
{ "resource": "" }
q1222
TCP._read_tcp_options
train
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 """ 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
python
{ "resource": "" }
q1223
TCP._read_mode_tsopt
train
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 """ temp = struct.unpack('>II', self._read_fileng(size)) data = dict( kind=kind, length=size, val=temp[0], ecr=temp[1], ) return data
python
{ "resource": "" }
q1224
TCP._read_mode_pocsp
train
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 """ 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
python
{ "resource": "" }
q1225
TCP._read_mode_acopt
train
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 """ temp = self._read_unpack(size) algo = chksum_opt.get(temp) data = dict( kind=kind, length=size, ac=algo, ) return data
python
{ "resource": "" }
q1226
TCP._read_mode_qsopt
train
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) """ 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
python
{ "resource": "" }
q1227
TCP._read_mode_utopt
train
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 """ 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
python
{ "resource": "" }
q1228
TCP._read_mode_tcpao
train
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 """ 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
python
{ "resource": "" }
q1229
TCP._read_mode_mptcp
train
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 """ 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
python
{ "resource": "" }
q1230
TCP._read_mptcp_capable
train
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) """ 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
python
{ "resource": "" }
q1231
TCP._read_mptcp_join
train
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 """ 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
python
{ "resource": "" }
q1232
TCP._read_join_syn
train
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 """ 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
python
{ "resource": "" }
q1233
TCP._read_join_ack
train
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 """ temp = self._read_fileng(20) data = dict( kind=kind, length=size + 1, subtype='MP_JOIN-ACK', join=dict( ack=dict( hmac=temp, ), ), ) return data
python
{ "resource": "" }
q1234
TCP._read_mptcp_add
train
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) """ 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
python
{ "resource": "" }
q1235
TCP._read_mptcp_remove
train
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) """ adid = [] for _ in size: adid.append(self._read_unpack(1)) data = dict( subtype='REMOVE_ADDR', removeaddr=dict( addrid=adid or None, ), ) return data
python
{ "resource": "" }
q1236
TCP._read_mptcp_prio
train
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) """ 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
python
{ "resource": "" }
q1237
extract
train
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 """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` """ if isinstance(layer, type) and issubclass(layer, Protocol): 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)
python
{ "resource": "" }
q1238
reassemble
train
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` """ 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}')
python
{ "resource": "" }
q1239
trace
train
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 """ str_check(fout or '', format or '') return TraceFlow(fout=fout, format=format, byteorder=byteorder, nanosecond=nanosecond)
python
{ "resource": "" }
q1240
IPv6_Frag.read_ipv6_frag
train
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 """ 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)
python
{ "resource": "" }
q1241
IPv4._read_ipv4_options
train
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 """ 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
python
{ "resource": "" }
q1242
IPv4._read_mode_route
train
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 """ 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
python
{ "resource": "" }
q1243
IPv4._read_mode_qs
train
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) """ 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
python
{ "resource": "" }
q1244
IPv4._read_mode_ts
train
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 """ 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
python
{ "resource": "" }
q1245
IPv4._read_mode_tr
train
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 """ 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
python
{ "resource": "" }
q1246
IPv4._read_mode_sec
train
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 """ 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
python
{ "resource": "" }
q1247
IPv4._read_mode_rsralt
train
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 """ 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
python
{ "resource": "" }
q1248
Header.read_header
train
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; """ _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
python
{ "resource": "" }
q1249
Frame.read_frame
train
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; """ # _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)
python
{ "resource": "" }
q1250
Frame._decode_next_layer
train
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 """ 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_
python
{ "resource": "" }
q1251
Raw.read_raw
train
def read_raw(self, length, *, error=None): """Read raw packet data.""" if length is None: length = len(self) raw = dict( packet=self._read_fileng(length), error=error or None, ) return raw
python
{ "resource": "" }
q1252
ipv6_hdr_len
train
def ipv6_hdr_len(ipv6): """Calculate length of headers before IPv6-Frag""" 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
python
{ "resource": "" }
q1253
packet2chain
train
def packet2chain(packet): """Fetch DPKT packet protocol chain.""" chain = [type(packet).__name__] payload = packet.data while not isinstance(payload, bytes): chain.append(type(payload).__name__) payload = payload.data return ':'.join(chain)
python
{ "resource": "" }
q1254
packet2dict
train
def packet2dict(packet, timestamp, *, data_link): """Convert DPKT packet into dict.""" 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), }
python
{ "resource": "" }
q1255
HTTPv2._read_http_none
train
def _read_http_none(self, size, kind, flag): """Read HTTP packet with unsigned type.""" 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
python
{ "resource": "" }
q1256
Extractor.run
train
def run(self): """Start extraction.""" 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()
python
{ "resource": "" }
q1257
Extractor.record_header
train
def record_header(self): """Read global header. - Extract global header. - Make Info object out of header properties. - Append Info. - Write plist file. """ 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
python
{ "resource": "" }
q1258
Extractor._cleanup
train
def _cleanup(self): """Cleanup after extraction & analysis.""" self._expkg = None self._extmp = None self._flag_e = True self._ifile.close()
python
{ "resource": "" }
q1259
Extractor._aftermathmp
train
def _aftermathmp(self): """Aftermath for multiprocessing.""" 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
python
{ "resource": "" }
q1260
Extractor._update_eof
train
def _update_eof(self): """Update EOF flag.""" self._aftermathmp() self._ifile.close() self._flag_e = True
python
{ "resource": "" }
q1261
Extractor._read_frame
train
def _read_frame(self): """Headquarters for frame reader.""" 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()
python
{ "resource": "" }
q1262
Extractor._default_read_frame
train
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. """ 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
python
{ "resource": "" }
q1263
Extractor._run_scapy
train
def _run_scapy(self, scapy_all): """Call scapy.all.sniff to extract PCAP files.""" # 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()
python
{ "resource": "" }
q1264
Extractor._scapy_read_frame
train
def _scapy_read_frame(self): """Read frames with Scapy.""" 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
python
{ "resource": "" }
q1265
Extractor._run_dpkt
train
def _run_dpkt(self, dpkt): """Call dpkt.pcap.Reader to extract PCAP files.""" # 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()
python
{ "resource": "" }
q1266
Extractor._run_pyshark
train
def _run_pyshark(self, pyshark): """Call pyshark.FileCapture to extract PCAP files.""" # 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()
python
{ "resource": "" }
q1267
Extractor._run_pipeline
train
def _run_pipeline(self, multiprocessing): """Use pipeline multiprocessing to extract PCAP files.""" 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]
python
{ "resource": "" }
q1268
Extractor._run_server
train
def _run_server(self, multiprocessing): """Use server multiprocessing to extract PCAP files.""" 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]
python
{ "resource": "" }
q1269
Extractor._server_analyse_frame
train
def _server_analyse_frame(self, *, mpkit, mpfrm, mprsm, mpbuf): """Analyse frame.""" 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)
python
{ "resource": "" }
q1270
HTTPv2.read_http
train
def read_http(self, length): """Read Hypertext Transfer Protocol version 2. Structure of HTTP/2 packet [RFC 7230]: +-----------------------------------------------+ | Length (24) | +---------------+---------------+---------------+ | Type (8) | Flags (8) | +-+-------------+---------------+-------------------------------+ |R| Stream Identifier (31) | +=+=============================================================+ | Frame Payload (0...) ... +---------------------------------------------------------------+ """ _plen = self._read_binary(3) _type = self._read_unpack(1) _flag = self._read_binary(1) _stid = self._read_binary(4)
python
{ "resource": "" }
q1271
TraceFlow.make_fout
train
def make_fout(fout='./tmp', fmt='pcap'): """Make root path for output. Positional arguments: * fout -- str, root path for output * fmt -- str, output format Returns: * output -- dumper of specified format """ if fmt == 'pcap': # output PCAP file from pcapkit.dumpkit import PCAP as output elif fmt == 'plist': # output PLIST file from dictdumper import PLIST as output elif fmt == 'json': # output JSON file from dictdumper import JSON as output elif fmt == 'tree': # output treeview text file from dictdumper import Tree as output fmt = 'txt' elif fmt == 'html': # output JavaScript file from dictdumper import JavaScript as output fmt = 'js' elif fmt == 'xml': # output XML file from dictdumper import XML as output else: # no output file from pcapkit.dumpkit import NotImplementedIO as output if fmt is not None: warnings.warn(f'Unsupported output format: {fmt}; disabled file output feature', FormatWarning, stacklevel=stacklevel()) return output, '' try: pathlib.Path(fout).mkdir(parents=True, exist_ok=True) except FileExistsError as error: if fmt is None: warnings.warn(error.strerror, FileWarning, stacklevel=stacklevel()) else: raise FileExists(*error.args) from None return output, fmt
python
{ "resource": "" }
q1272
TraceFlow.dump
train
def dump(self, packet): """Dump frame to output files. Positional arguments: * packet -- dict, a flow packet |-- (str) protocol -- data link type from global header |-- (int) index -- frame number |-- (Info) frame -- extracted frame info |-- (bool) syn -- TCP synchronise (SYN) flag |-- (bool) fin -- TCP finish (FIN) flag |-- (str) src -- source IP |-- (int) srcport -- TCP source port |-- (str) dst -- destination IP |-- (int) dstport -- TCP destination port |-- (numbers.Real) timestamp -- frame timestamp """ # fetch flow label output = self.trace(packet, _check=False, _output=True) # dump files output(packet['frame'], name=f"Frame {packet['index']}", byteorder=self._endian, nanosecond=self._nnsecd)
python
{ "resource": "" }
q1273
TraceFlow.trace
train
def trace(self, packet, *, _check=True, _output=False): """Trace packets. Positional arguments: * packet -- dict, a flow packet Keyword arguments: * _check -- bool, flag if run validations * _output -- bool, flag if has formatted dumper """ self._newflg = True if _check: pkt_check(packet) info = Info(packet) # Buffer Identifier BUFID = tuple(sorted([str(info.src), str(info.srcport), # pylint: disable=E1101 str(info.dst), str(info.dstport)])) # pylint: disable=E1101 # SYN = info.syn # Synchronise Flag (Establishment) # Finish Flag (Termination) FIN = info.fin # pylint: disable=E1101 # # when SYN is set, reset buffer of this seesion # if SYN and BUFID in self._buffer: # temp = self._buffer.pop(BUFID) # temp['fpout'] = (self._fproot, self._fdpext) # temp['index'] = tuple(temp['index']) # self._stream.append(Info(temp)) # initialise buffer with BUFID if BUFID not in self._buffer: label = f'{info.src}_{info.srcport}-{info.dst}_{info.dstport}-{info.timestamp}' # pylint: disable=E1101 self._buffer[BUFID] = dict( fpout=self._foutio(f'{self._fproot}/{label}.{self._fdpext}', protocol=info.protocol), # pylint: disable=E1101 index=list(), label=label, ) # trace frame record self._buffer[BUFID]['index'].append(info.index) # pylint: disable=E1101 fpout = self._buffer[BUFID]['fpout'] label = self._buffer[BUFID]['label'] # when FIN is set, submit buffer of this session if FIN: buf = self._buffer.pop(BUFID) # fpout, label = buf['fpout'], buf['label'] if self._fdpext: buf['fpout'] = f'{self._fproot}/{label}.{self._fdpext}' else: del buf['fpout'] buf['index'] = tuple(buf['index']) self._stream.append(Info(buf)) # return label or output object return fpout if _output else label
python
{ "resource": "" }
q1274
TraceFlow.submit
train
def submit(self): """Submit traced TCP flows.""" self._newflg = False ret = list() for buf in self._buffer.values(): buf = copy.deepcopy(buf) if self._fdpext: buf['fpout'] = f"{self._fproot}/{buf['label']}.{self._fdpext}" else: del buf['fpout'] buf['index'] = tuple(buf['index']) ret.append(Info(buf)) ret += self._stream return tuple(ret)
python
{ "resource": "" }
q1275
AH.read_ah
train
def read_ah(self, length, version, extension): """Read Authentication Header. Structure of AH header [RFC 4302]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Payload Len | RESERVED | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Security Parameters Index (SPI) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Sequence Number Field | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | + Integrity Check Value-ICV (variable) | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 ah.next Next Header 1 8 ah.length Payload Length 2 16 - Reserved (must be zero) 4 32 ah.spi Security Parameters Index (SPI) 8 64 ah.seq Sequence Number Field 12 96 ah.icv Integrity Check Value (ICV) """ if length is None: length = len(self) _next = self._read_protos(1) _plen = self._read_unpack(1) _resv = self._read_fileng(2) _scpi = self._read_unpack(4) _dsnf = self._read_unpack(4) # ICV length & value _tlen = _plen * 4 - 2 _vlen = _tlen - 12 _chkv = self._read_fileng(_vlen) ah = dict( next=_next, length=_tlen, spi=_scpi, seq=_dsnf, icv=_chkv, ) if version == 6: _plen = 8 - (_tlen % 8) elif version == 4: _plen = 4 - (_tlen % 4) else: raise VersionError(f'Unknown IP version {version}') if _plen: # explicit padding in need padding = self._read_binary(_plen) if any((int(bit, base=2) for bit in padding)): raise ProtocolError(f'{self.alias}: invalid format') length -= ah['length'] ah['packet'] = self._read_packet(header=ah['length'], payload=length) if extension: self._protos = None return ah return self._decode_next_layer(ah, _next, length)
python
{ "resource": "" }
q1276
Ethernet.read_ethernet
train
def read_ethernet(self, length): """Read Ethernet Protocol. Structure of Ethernet Protocol header [RFC 7042]: Octets Bits Name Description 0 0 eth.dst Destination MAC Address 1 8 eth.src Source MAC Address 2 16 eth.type Protocol (Internet Layer) """ if length is None: length = len(self) _dstm = self._read_mac_addr() _srcm = self._read_mac_addr() _type = self._read_protos(2) ethernet = dict( dst=_dstm, src=_srcm, type=_type, ) length -= 14 ethernet['packet'] = self._read_packet(header=14, payload=length) return self._decode_next_layer(ethernet, _type, length)
python
{ "resource": "" }
q1277
Ethernet._read_mac_addr
train
def _read_mac_addr(self): """Read MAC address.""" _byte = self._read_fileng(6) _addr = '-'.join(textwrap.wrap(_byte.hex(), 2)) return _addr
python
{ "resource": "" }
q1278
packet2dict
train
def packet2dict(packet): """Convert PyShark packet into dict.""" dict_ = dict() frame = packet.frame_info for field in frame.field_names: dict_[field] = getattr(frame, field) tempdict = dict_ for layer in packet.layers: tempdict[layer.layer_name.upper()] = dict() tempdict = tempdict[layer.layer_name.upper()] for field in layer.field_names: tempdict[field] = getattr(layer, field) return dict_
python
{ "resource": "" }
q1279
packet2chain
train
def packet2chain(packet): """Fetch Scapy packet protocol chain.""" if scapy_all is None: raise ModuleNotFound("No module named 'scapy'", name='scapy') chain = [packet.name] payload = packet.payload while not isinstance(payload, scapy_all.packet.NoPayload): chain.append(payload.name) payload = payload.payload return ':'.join(chain)
python
{ "resource": "" }
q1280
packet2dict
train
def packet2dict(packet, *, count=NotImplemented): """Convert Scapy packet into dict.""" if scapy_all is None: raise ModuleNotFound("No module named 'scapy'", name='scapy') def wrapper(packet): dict_ = packet.fields payload = packet.payload if not isinstance(payload, scapy_all.packet.NoPayload): dict_[payload.name] = wrapper(payload) return dict_ return { 'packet': bytes(packet), packet.name: wrapper(packet), }
python
{ "resource": "" }
q1281
tcp_reassembly
train
def tcp_reassembly(packet, *, count=NotImplemented): """Store data for TCP reassembly.""" if 'TCP' in packet: ip = packet['IP'] if 'IP' in packet else packet['IPv6'] tcp = packet['TCP'] 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 syn=bool(tcp.flags.S), # synchronise flag fin=bool(tcp.flags.F), # finish flag rst=bool(tcp.flags.R), # reset connection flag payload=bytearray(bytes(tcp.payload)), # raw bytearray type payload ) raw_len = len(tcp.payload) # 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
python
{ "resource": "" }
q1282
HOPOPT.read_hopopt
train
def read_hopopt(self, length, extension): """Read IPv6 Hop-by-Hop Options. Structure of HOPOPT header [RFC 8200]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | | . . . Options . . . | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.next Next Header 1 8 hopopt.length Header Extensive Length 2 16 hopopt.options Options """ if length is None: length = len(self) _next = self._read_protos(1) _hlen = self._read_unpack(1) # _opts = self._read_fileng(_hlen*8+6) hopopt = dict( next=_next, length=(_hlen + 1) * 8, ) options = self._read_hopopt_options(_hlen * 8 + 6) hopopt['options'] = options[0] # tuple of option acronyms hopopt.update(options[1]) # merge option info to buffer length -= hopopt['length'] hopopt['packet'] = self._read_packet(header=hopopt['length'], payload=length) if extension: self._protos = None return hopopt return self._decode_next_layer(hopopt, _next, length)
python
{ "resource": "" }
q1283
HOPOPT._read_hopopt_options
train
def _read_hopopt_options(self, length): """Read HOPOPT options. Positional arguments: * length -- int, length of options Returns: * dict -- extracted HOPOPT options """ counter = 0 # length of read options optkind = list() # option type list options = dict() # dict of option data while counter < length: # break when eol triggered code = self._read_unpack(1) if not code: break # extract parameter abbr, desc = _HOPOPT_OPT.get(code, ('none', 'Unassigned')) data = _HOPOPT_PROC(abbr)(self, code, desc=desc) enum = _OPT_TYPE.get(code) # record parameter data counter += data['length'] if enum in optkind: if isinstance(options[abbr], tuple): options[abbr] += (Info(data),) else: options[abbr] = (Info(options[abbr]), Info(data)) else: optkind.append(enum) options[abbr] = data # check threshold if counter != length: raise ProtocolError(f'{self.alias}: invalid format') return tuple(optkind), options
python
{ "resource": "" }
q1284
HOPOPT._read_opt_pad
train
def _read_opt_pad(self, code, *, desc): """Read HOPOPT padding options. Structure of HOPOPT padding options [RFC 8200]: * Pad1 Option: +-+-+-+-+-+-+-+-+ | 0 | +-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.pad.type Option Type 0 0 hopopt.pad.type.value Option Number 0 0 hopopt.pad.type.action Action (00) 0 2 hopopt.pad.type.change Change Flag (0) * PadN Option: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - - | 1 | Opt Data Len | Option Data +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - - Octets Bits Name Description 0 0 hopopt.pad.type Option Type 0 0 hopopt.pad.type.value Option Number 0 0 hopopt.pad.type.action Action (00) 0 2 hopopt.pad.type.change Change Flag (0) 1 8 hopopt.opt.length Length of Option Data 2 16 hopopt.pad.padding Padding """ _type = self._read_opt_type(code) if code == 0: opt = dict( desc=desc, type=_type, length=1, ) elif code == 1: _size = self._read_unpack(1) _padn = self._read_fileng(_size) opt = dict( desc=desc, type=_type, length=_size + 2, padding=_padn, ) else: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') return opt
python
{ "resource": "" }
q1285
HOPOPT._read_opt_tun
train
def _read_opt_tun(self, code, *, desc): """Read HOPOPT Tunnel Encapsulation Limit option. Structure of HOPOPT Tunnel Encapsulation Limit option [RFC 2473]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header |Hdr Ext Len = 0| Opt Type = 4 |Opt Data Len=1 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Tun Encap Lim |PadN Opt Type=1|Opt Data Len=1 | 0 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.tun.type Option Type 0 0 hopopt.tun.type.value Option Number 0 0 hopopt.tun.type.action Action (00) 0 2 hopopt.tun.type.change Change Flag (0) 1 8 hopopt.tun.length Length of Option Data 2 16 hopopt.tun.limit Tunnel Encapsulation Limit """ _type = self._read_opt_type(code) _size = self._read_unpack(1) if _size != 1: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _limt = self._read_unpack(1) opt = dict( desc=desc, type=_type, length=_size + 2, limit=_limt, ) return opt
python
{ "resource": "" }
q1286
HOPOPT._read_opt_ra
train
def _read_opt_ra(self, code, *, desc): """Read HOPOPT Router Alert option. Structure of HOPOPT Router Alert option [RFC 2711]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0 0 0|0 0 1 0 1|0 0 0 0 0 0 1 0| Value (2 octets) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.ra.type Option Type 0 0 hopopt.ra.type.value Option Number 0 0 hopopt.ra.type.action Action (00) 0 2 hopopt.ra.type.change Change Flag (0) 1 8 hopopt.opt.length Length of Option Data 2 16 hopopt.ra.value Value """ _type = self._read_opt_type(code) _size = self._read_unpack(1) if _size != 2: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _rval = self._read_unpack(2) if 4 <= _rval <= 35: _dscp = f'Aggregated Reservation Nesting Level {_rval-4}' # [RFC 3175] elif 36 <= _rval <= 67: _dscp = f'QoS NSLP Aggregation Level {_rval-36}' # [RFC 5974] elif 65503 <= _rval <= 65534: _dscp = 'Reserved for experimental use' # [RFC 5350] else: _dscp = _ROUTER_ALERT.get(_rval, 'Unassigned') opt = dict( desc=desc, type=_type, length=_size + 2, value=_rval, alert=_dscp, ) return opt
python
{ "resource": "" }
q1287
HOPOPT._read_opt_calipso
train
def _read_opt_calipso(self, code, *, desc): """Read HOPOPT CALIPSO option. Structure of HOPOPT CALIPSO option [RFC 5570]: ------------------------------------------------------------ | Next Header | Hdr Ext Len | Option Type | Option Length| +-------------+---------------+-------------+--------------+ | CALIPSO Domain of Interpretation | +-------------+---------------+-------------+--------------+ | Cmpt Length | Sens Level | Checksum (CRC-16) | +-------------+---------------+-------------+--------------+ | Compartment Bitmap (Optional; variable length) | +-------------+---------------+-------------+--------------+ Octets Bits Name Description 0 0 hopopt.calipso.type Option Type 0 0 hopopt.calipso.type.value Option Number 0 0 hopopt.calipso.type.action Action (00) 0 2 hopopt.calipso.type.change Change Flag (0) 1 8 hopopt.calipso.length Length of Option Data 2 16 hopopt.calipso.domain CALIPSO Domain of Interpretation 6 48 hopopt.calipso.cmpt_len Cmpt Length 7 56 hopopt.calipso.level Sens Level 8 64 hopopt.calipso.chksum Checksum (CRC-16) 9 72 hopopt.calipso.bitmap Compartment Bitmap """ _type = self._read_opt_type(code) _size = self._read_unpack(1) if _size < 8 and _size % 8 != 0: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _cmpt = self._read_unpack(4) _clen = self._read_unpack(1) if _clen % 2 != 0: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _sens = self._read_unpack(1) _csum = self._read_fileng(2) opt = dict( desc=desc, type=_type, length=_size + 2, domain=_cmpt, cmpt_len=_clen * 4, level=_sens, chksum=_csum, ) if _clen: _bmap = list() for _ in range(_clen // 2): _bmap.append(self._read_binary(8)) opt['bitmap'] = tuple(_bmap) _plen = _size - _clen * 4 - 8 if _plen: self._read_fileng(_plen) return opt
python
{ "resource": "" }
q1288
HOPOPT._read_opt_smf_dpd
train
def _read_opt_smf_dpd(self, code, *, desc): """Read HOPOPT SMF_DPD option. Structure of HOPOPT SMF_DPD option [RFC 5570]: * IPv6 SMF_DPD Option Header in I-DPD mode 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ... |0|0|0| 01000 | Opt. Data Len | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0|TidTy| TidLen| TaggerId (optional) ... | +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | Identifier ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.smf_dpd.type Option Type 0 0 hopopt.smf_dpd.type.value Option Number 0 0 hopopt.smf_dpd.type.action Action (00) 0 2 hopopt.smf_dpd.type.change Change Flag (0) 1 8 hopopt.smf_dpd.length Length of Option Data 2 16 hopopt.smf_dpd.dpd_type DPD Type (0) 2 17 hopopt.smf_dpd.tid_type TaggerID Type 2 20 hopopt.smf_dpd.tid_len TaggerID Length 3 24 hopopt.smf_dpd.tid TaggerID ? ? hopopt.smf_dpd.id Identifier * IPv6 SMF_DPD Option Header in H-DPD Mode 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ... |0|0|0| OptType | Opt. Data Len | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1| Hash Assist Value (HAV) ... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.smf_dpd.type Option Type 0 0 hopopt.smf_dpd.type.value Option Number 0 0 hopopt.smf_dpd.type.action Action (00) 0 2 hopopt.smf_dpd.type.change Change Flag (0) 1 8 hopopt.smf_dpd.length Length of Option Data 2 16 hopopt.smf_dpd.dpd_type DPD Type (1) 2 17 hopopt.smf_dpd.hav Hash Assist Value """ _type = self._read_opt_type(code) _size = self._read_unpack(1) _tidd = self._read_binary(1) if _tidd[0] == '0': _mode = 'I-DPD' _tidt = _TID_TYPE.get(_tidd[1:4], 'Unassigned') _tidl = int(_tidd[4:], base=2) if _tidt == 'NULL': if _tidl != 0: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _iden = self._read_fileng(_size-1) opt = dict( desc=desc, type=_type, length=_size + 2, dpd_type=_mode, tid_type=_tidt, tid_len=_tidl, id=_iden, ) elif _tidt == 'IPv4': if _tidl != 3: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _tidf = self._read_fileng(4) _iden = self._read_fileng(_size-4) opt = dict( desc=desc, type=_type, length=_size + 2, dpd_type=_mode, tid_type=_tidt, tid_len=_tidl, tid=ipaddress.ip_address(_tidf), id=_iden, ) elif _tidt == 'IPv6': if _tidl != 15: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _tidf = self._read_fileng(15) _iden = self._read_fileng(_size-15) opt = dict( desc=desc, type=_type, length=_size + 2, dpd_type=_mode, tid_type=_tidt, tid_len=_tidl, tid=ipaddress.ip_address(_tidf), id=_iden, ) else: _tidf = self._read_unpack(_tidl+1) _iden = self._read_fileng(_size-_tidl-2) opt = dict( desc=desc, type=_type, length=_size + 2, dpd_type=_mode, tid_type=_tidt, tid_len=_tidl, tid=_tidf, id=_iden, ) elif _tidd[0] == '1': _data = self._read_binary(_size-1) opt = dict( desc=desc, type=_type, length=_size + 2, dpd_type=_mode, tid_type=_tidt, hav=_tidd[1:] + _data, ) else: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') return opt
python
{ "resource": "" }
q1289
HOPOPT._read_opt_pdm
train
def _read_opt_pdm(self, code, *, desc): """Read HOPOPT PDM option. Structure of HOPOPT PDM option [RFC 8250]: 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 Type | Option Length | ScaleDTLR | ScaleDTLS | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | PSN This Packet | PSN Last Received | |-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Delta Time Last Received | Delta Time Last Sent | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.pdm.type Option Type 0 0 hopopt.pdm.type.value Option Number 0 0 hopopt.pdm.type.action Action (00) 0 2 hopopt.pdm.type.change Change Flag (0) 1 8 hopopt.pdm.length Length of Option Data 2 16 hopopt.pdm.scaledtlr Scale Delta Time Last Received 3 24 hopopt.pdm.scaledtls Scale Delta Time Last Sent 4 32 hopopt.pdm.psntp Packet Sequence Number This Packet 6 48 hopopt.pdm.psnlr Packet Sequence Number Last Received 8 64 hopopt.pdm.deltatlr Delta Time Last Received 10 80 hopopt.pdm.deltatls Delta Time Last Sent """ _type = self._read_opt_type(code) _size = self._read_unpack(1) if _size != 10: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _stlr = self._read_unpack(1) _stls = self._read_unpack(1) _psnt = self._read_unpack(2) _psnl = self._read_unpack(2) _dtlr = self._read_unpack(2) _dtls = self._read_unpack(2) opt = dict( desc=desc, type=_type, length=_size + 2, scaledtlr=datetime.timedelta(seconds=_stlr), scaledtls=datetime.timedelta(seconds=_stls), psntp=_psnt, psnlr=_psnl, deltatlr=datetime.timedelta(seconds=_dtlr), deltatls=datetime.timedelta(seconds=_dtls), ) return opt
python
{ "resource": "" }
q1290
HOPOPT._read_opt_qs
train
def _read_opt_qs(self, code, *, desc): """Read HOPOPT Quick Start option. Structure of HOPOPT Quick-Start 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=6 | 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=6 | Func. | Rate | Not Used | | | | 1000 | Report| | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | QS Nonce | R | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.qs.type Option Type 0 0 hopopt.qs.type.value Option Number 0 0 hopopt.qs.type.action Action (00) 0 2 hopopt.qs.type.change Change Flag (1) 1 8 hopopt.qs.length Length of Option Data 2 16 hopopt.qs.func Function (0/8) 2 20 hopopt.qs.rate Rate Request / Report (in Kbps) 3 24 hopopt.qs.ttl QS TTL / None 4 32 hopopt.qs.nounce QS Nounce 7 62 - Reserved """ _type = self._read_opt_type(code) _size = self._read_unpack(1) if _size != 6: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _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 {code}] invalid format') data = dict( type=_type, length=_size + 2, func=_QS_FUNC.get(_func), rate=40000 * (2 ** _rate) / 1000, ttl=None if _func else _rate, nounce=_qsnn, ) return data
python
{ "resource": "" }
q1291
HOPOPT._read_opt_rpl
train
def _read_opt_rpl(self, code, *, desc): """Read HOPOPT RPL option. Structure of HOPOPT RPL option [RFC 6553]: 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 Type | Opt Data Len | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |O|R|F|0|0|0|0|0| RPLInstanceID | SenderRank | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | (sub-TLVs) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.rpl.type Option Type 0 0 hopopt.rpl.type.value Option Number 0 0 hopopt.rpl.type.action Action (01) 0 2 hopopt.rpl.type.change Change Flag (1) 1 8 hopopt.rpl.length Length of Option Data 2 16 hopopt.rpl.flags RPL Option Flags 2 16 hopopt.rpl.flags.down Down Flag 2 17 hopopt.rpl.flags.rank_error Rank-Error Flag 2 18 hopopt.rpl.flags.fwd_error Forwarding-Error Flag 3 24 hopopt.rpl.id RPLInstanceID 4 32 hopopt.rpl.rank SenderRank 6 48 hopopt.rpl.data Sub-TLVs """ _type = self._read_opt_type(code) _size = self._read_unpack(1) if _size < 4: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _flag = self._read_binary(1) _rpld = self._read_unpack(1) _rank = self._read_unpack(2) opt = dict( desc=desc, type=_type, length=_size + 2, flags=dict( down=True if int(_flag[0], base=2) else False, rank_error=True if int(_flag[1], base=2) else False, fwd_error=True if int(_flag[2], base=2) else False, ), id=_rpld, rank=_rank, ) if _size > 4: opt['data'] = self._read_fileng(_size-4) return opt
python
{ "resource": "" }
q1292
HOPOPT._read_opt_ilnp
train
def _read_opt_ilnp(self, code, *, desc): """Read HOPOPT ILNP Nonce option. Structure of HOPOPT ILNP Nonce option [RFC 6744]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | Option Type | Option Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ / Nonce Value / +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.ilnp.type Option Type 0 0 hopopt.ilnp.type.value Option Number 0 0 hopopt.ilnp.type.action Action (10) 0 2 hopopt.ilnp.type.change Change Flag (0) 1 8 hopopt.ilnp.length Length of Option Data 2 16 hopopt.ilnp.value Nonce Value """ _type = self._read_opt_type(code) _size = self._read_unpack(1) _nval = self._read_fileng(_size) opt = dict( desc=desc, type=_type, length=_size + 2, value=_nval, ) return opt
python
{ "resource": "" }
q1293
HOPOPT._read_opt_lio
train
def _read_opt_lio(self, code, *, desc): """Read HOPOPT Line-Identification option. Structure of HOPOPT Line-Identification option [RFC 6788]: 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 Type | Option Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | LineIDLen | Line ID... +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.lio.type Option Type 0 0 hopopt.lio.type.value Option Number 0 0 hopopt.lio.type.action Action (10) 0 2 hopopt.lio.type.change Change Flag (0) 1 8 hopopt.lio.length Length of Option Data 2 16 hopopt.lio.lid_len Line ID Length 3 24 hopopt.lio.lid Line ID """ _type = self._read_opt_type(code) _size = self._read_unpack(1) _llen = self._read_unpack(1) _line = self._read_fileng(_llen) opt = dict( desc=desc, type=_type, length=_size + 2, lid_len=_llen, lid=_line, ) _plen = _size - _llen if _plen: self._read_fileng(_plen) return opt
python
{ "resource": "" }
q1294
HOPOPT._read_opt_jumbo
train
def _read_opt_jumbo(self, code, *, desc): """Read HOPOPT Jumbo Payload option. Structure of HOPOPT Jumbo Payload option [RFC 2675]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Option Type | Opt Data Len | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Jumbo Payload Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.jumbo.type Option Type 0 0 hopopt.jumbo.type.value Option Number 0 0 hopopt.jumbo.type.action Action (11) 0 2 hopopt.jumbo.type.change Change Flag (0) 1 8 hopopt.jumbo.length Length of Option Data 2 16 hopopt.jumbo.payload_len Jumbo Payload Length """ _type = self._read_opt_type(code) _size = self._read_unpack(1) if _size != 4: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _jlen = self._read_unpack(4) opt = dict( desc=desc, type=_type, length=_size + 2, payload_len=_jlen, ) return opt
python
{ "resource": "" }
q1295
HOPOPT._read_opt_home
train
def _read_opt_home(self, code, *, desc): """Read HOPOPT Home Address option. Structure of HOPOPT Home Address option [RFC 6275]: 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 Type | Option Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | + + | | + Home Address + | | + + | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.home.type Option Type 0 0 hopopt.home.type.value Option Number 0 0 hopopt.home.type.action Action (11) 0 2 hopopt.home.type.change Change Flag (0) 1 8 hopopt.home.length Length of Option Data 2 16 hopopt.home.ip Home Address """ _type = self._read_opt_type(code) _size = self._read_unpack(1) if _size != 16: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _addr = self._read_fileng(16) opt = dict( desc=desc, type=_type, length=_size + 2, ip=ipaddress.ip_address(_addr), ) return opt
python
{ "resource": "" }
q1296
HOPOPT._read_opt_ip_dff
train
def _read_opt_ip_dff(self, code, *, desc): """Read HOPOPT IP_DFF option. Structure of HOPOPT IP_DFF option [RFC 6971]: 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 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | OptTypeDFF | OptDataLenDFF | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |VER|D|R|0|0|0|0| Sequence Number | Pad1 | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 hopopt.ip_dff.type Option Type 0 0 hopopt.ip_dff.type.value Option Number 0 0 hopopt.ip_dff.type.action Action (11) 0 2 hopopt.ip_dff.type.change Change Flag (1) 1 8 hopopt.ip_dff.length Length of Option Data 2 16 hopopt.ip_dff.version Version 2 18 hopopt.ip_dff.flags Flags 2 18 hopopt.ip_dff.flags.dup DUP Flag 2 19 hopopt.ip_dff.flags.ret RET Flag 2 20 - Reserved 3 24 hopopt.ip_dff.seq Sequence Number """ _type = self._read_opt_type(code) _size = self._read_unpack(1) if _size != 2: raise ProtocolError(f'{self.alias}: [Optno {code}] invalid format') _verf = self._read_binary(1) _seqn = self._read_unpack(2) opt = dict( desc=desc, type=_type, length=_size + 2, version=_verf[:2], flags=dict( dup=True if int(_verf[2], base=2) else False, ret=True if int(_verf[3], base=2) else False, ), seq=_seqn, ) return opt
python
{ "resource": "" }
q1297
IPv6_Opts.read_ipv6_opts
train
def read_ipv6_opts(self, length, extension): """Read Destination Options for IPv6. Structure of IPv6-Opts header [RFC 8200]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Next Header | Hdr Ext Len | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | | . . . Options . . . | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Octets Bits Name Description 0 0 opt.next Next Header 1 8 opt.length Header Extensive Length 2 16 opt.options Options """ if length is None: length = len(self) _next = self._read_protos(1) _hlen = self._read_unpack(1) # _opts = self._read_fileng(_hlen*8+6) ipv6_opts = dict( next=_next, length=(_hlen + 1) * 8, ) options = self._read_ipv6_opts_options(_hlen * 8 + 6) ipv6_opts['options'] = options[0] # tuple of option acronyms ipv6_opts.update(options[1]) # merge option info to buffer length -= ipv6_opts['length'] ipv6_opts['packet'] = self._read_packet(header=ipv6_opts['length'], payload=length) if extension: self._protos = None return ipv6_opts return self._decode_next_layer(ipv6_opts, _next, length)
python
{ "resource": "" }
q1298
IPv6_Opts._read_ipv6_opts_options
train
def _read_ipv6_opts_options(self, length): """Read IPv6_Opts options. Positional arguments: * length -- int, length of options Returns: * dict -- extracted IPv6_Opts options """ counter = 0 # length of read options optkind = list() # option type list options = dict() # dict of option data while counter < length: # break when eol triggered code = self._read_unpack(1) if not code: break # extract parameter abbr, desc = _IPv6_Opts_OPT.get(code, ('None', 'Unassigned')) data = _IPv6_Opts_PROC(abbr)(self, code, desc=desc) enum = _OPT_TYPE.get(code) # record parameter data counter += data['length'] if enum in optkind: if isinstance(options[abbr], tuple): options[abbr] += (Info(data),) else: options[abbr] = (Info(options[abbr]), Info(data)) else: optkind.append(enum) options[abbr] = data # check threshold if counter != length: raise ProtocolError(f'{self.alias}: invalid format') return tuple(optkind), options
python
{ "resource": "" }
q1299
IPv6_Opts._read_opt_none
train
def _read_opt_none(self, code, *, desc): """Read IPv6_Opts unassigned options. Structure of IPv6_Opts unassigned options [RFC 8200]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - - | Option Type | Opt Data Len | Option Data +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+- - - - - - - - - Octets Bits Name Description 0 0 ipv6_opts.opt.type Option Type 0 0 ipv6_opts.opt.type.value Option Number 0 0 ipv6_opts.opt.type.action Action (00-11) 0 2 ipv6_opts.opt.type.change Change Flag (0/1) 1 8 ipv6_opts.opt.length Length of Option Data 2 16 ipv6_opts.opt.data Option Data """ _type = self._read_opt_type(code) _size = self._read_unpack(1) _data = self._read_fileng(_size) opt = dict( desc=_IPv6_Opts_NULL.get(code, desc), type=_type, length=_size + 2, data=_data, ) return opt
python
{ "resource": "" }