text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Return a list of non-primitive types used by this object. <END_TASK> <USER_TASK:> Description: def _get_type_list(self, props): """Return a list of non-primitive types used by this object."""
type_list = [] for k, v in list(props.items()): t = self._get_property_type(v) if t is not None: type_list.append(t) return sorted(type_list)
<SYSTEM_TASK:> Output common validator types based on usage. <END_TASK> <USER_TASK:> Description: def _output_validators(self): """Output common validator types based on usage."""
if self._walk_for_type('Boolean'): print("from .validators import boolean") if self._walk_for_type('Integer'): print("from .validators import integer") vlist = self.override.get_validator_list() for override in vlist: if override.startswith('common/')...
<SYSTEM_TASK:> Build a tree of non-primitive typed dependency order. <END_TASK> <USER_TASK:> Description: def build_tree(self, name, props, resource_name=None): """Build a tree of non-primitive typed dependency order."""
n = Node(name, props, resource_name) prop_type_list = self._get_type_list(props) if not prop_type_list: return n prop_type_list = sorted(prop_type_list) for prop_name in prop_type_list: if prop_name == 'Tag': continue child = s...
<SYSTEM_TASK:> Returns the list of all troposphere members we are able to <END_TASK> <USER_TASK:> Description: def inspect_members(self): """ Returns the list of all troposphere members we are able to construct """
if not self._inspect_members: TemplateGenerator._inspect_members = \ self._import_all_troposphere_modules() return self._inspect_members
<SYSTEM_TASK:> Attempts to return troposphere class that represents Type of <END_TASK> <USER_TASK:> Description: def _get_resource_type_cls(self, name, resource): """Attempts to return troposphere class that represents Type of provided resource. Attempts to find the troposphere class who's `reso...
# If provided resource does not have `Type` field if 'Type' not in resource: raise ResourceTypeNotDefined(name) # Attempt to find troposphere resource with: # `resource_type` == resource['Type'] try: return self.inspect_resources[resource['Type']] ...
<SYSTEM_TASK:> Converts any object to its troposphere equivalent, if applicable. <END_TASK> <USER_TASK:> Description: def _convert_definition(self, definition, ref=None, cls=None): """ Converts any object to its troposphere equivalent, if applicable. This function will recurse into lists and map...
if isinstance(definition, Mapping): if 'Type' in definition: # this is an AWS Resource expected_type = None if cls is not None: expected_type = cls else: # if the user uses the custom way to name custom resourc...
<SYSTEM_TASK:> Returns an instance of `cls` with `args` passed as arguments. <END_TASK> <USER_TASK:> Description: def _create_instance(self, cls, args, ref=None): """ Returns an instance of `cls` with `args` passed as arguments. Recursively inspects `args` to create nested objects and functions...
if isinstance(cls, Sequence): if len(cls) == 1: # a list of 1 type means we must provide a list of such objects if (isinstance(args, basestring) or not isinstance(args, Sequence)): args = [args] return [self...
<SYSTEM_TASK:> Inspects the definition and returns a copy of it that is updated <END_TASK> <USER_TASK:> Description: def _normalize_properties(self, definition): """ Inspects the definition and returns a copy of it that is updated with any special property such as Condition, UpdatePolicy and the...
args = definition.get('Properties', {}).copy() if 'Condition' in definition: args.update({'Condition': definition['Condition']}) if 'UpdatePolicy' in definition: # there's only 1 kind of UpdatePolicy; use it args.update({'UpdatePolicy': self._create_instance(...
<SYSTEM_TASK:> Provides special handling for the autoscaling.Metadata object <END_TASK> <USER_TASK:> Description: def _generate_autoscaling_metadata(self, cls, args): """ Provides special handling for the autoscaling.Metadata object """
assert isinstance(args, Mapping) init_config = self._create_instance( cloudformation.InitConfig, args['AWS::CloudFormation::Init']['config']) init = self._create_instance( cloudformation.Init, {'config': init_config}) auth = None if 'AWS::Clou...
<SYSTEM_TASK:> Imports all troposphere modules and returns them <END_TASK> <USER_TASK:> Description: def _import_all_troposphere_modules(self): """ Imports all troposphere modules and returns them """
dirname = os.path.join(os.path.dirname(__file__)) module_names = [ pkg_name for importer, pkg_name, is_pkg in pkgutil.walk_packages([dirname], prefix="troposphere.") if not is_pkg and pkg_name not in self.EXCLUDE_MODULES] module_names.append('trop...
<SYSTEM_TASK:> Returns windows interfaces through GetAdaptersAddresses. <END_TASK> <USER_TASK:> Description: def get_windows_if_list(extended=False): """Returns windows interfaces through GetAdaptersAddresses. params: - extended: include anycast and multicast IPv6 (default False)"""
# Should work on Windows XP+ def _get_mac(x): size = x["physical_address_length"] if size != 6: return "" data = bytearray(x["physical_address"]) return str2mac(bytes(data)[:size]) def _get_ips(x): unicast = x['first_unicast_address'] anycast = x...
<SYSTEM_TASK:> Returns all available IPs matching to interfaces, using the windows system. <END_TASK> <USER_TASK:> Description: def get_ips(v6=False): """Returns all available IPs matching to interfaces, using the windows system. Should only be used as a WinPcapy fallback."""
res = {} for iface in six.itervalues(IFACES): ips = [] for ip in iface.ips: if v6 and ":" in ip: ips.append(ip) elif not v6 and ":" not in ip: ips.append(ip) res[iface] = ips return res
<SYSTEM_TASK:> Internal util to run pcap control command <END_TASK> <USER_TASK:> Description: def _pcap_service_control(action, askadmin=True): """Internal util to run pcap control command"""
command = action + ' ' + pcap_service_name() res, code = _exec_cmd(_encapsulate_admin(command) if askadmin else command) if code != 0: warning(res.decode("utf8", errors="ignore")) return (code == 0)
<SYSTEM_TASK:> Get the device pcap name by device name or Scapy NetworkInterface <END_TASK> <USER_TASK:> Description: def pcapname(dev): """Get the device pcap name by device name or Scapy NetworkInterface """
if isinstance(dev, NetworkInterface): if dev.is_invalid(): return None return dev.pcap_name try: return IFACES.dev_from_name(dev).pcap_name except ValueError: return IFACES.dev_from_pcapname(dev).pcap_name
<SYSTEM_TASK:> Retrieve Windows routes through a GetIpForwardTable call. <END_TASK> <USER_TASK:> Description: def _read_routes_c_v1(): """Retrieve Windows routes through a GetIpForwardTable call. This is compatible with XP but won't get IPv6 routes."""
def _extract_ip(obj): return inet_ntop(socket.AF_INET, struct.pack("<I", obj)) routes = [] for route in GetIpForwardTable(): ifIndex = route['ForwardIfIndex'] dest = route['ForwardDest'] netmask = route['ForwardMask'] nexthop = _extract_ip(route['ForwardNextHop']) ...
<SYSTEM_TASK:> Returns all IPv6 addresses found on the computer <END_TASK> <USER_TASK:> Description: def in6_getifaddr(): """ Returns all IPv6 addresses found on the computer """
ifaddrs = [] ip6s = get_ips(v6=True) for iface in ip6s: ips = ip6s[iface] for ip in ips: scope = in6_getscope(ip) ifaddrs.append((ip, scope, iface)) # Appends Npcap loopback if available if conf.use_npcap and scapy.consts.LOOPBACK_INTERFACE: ifaddrs.a...
<SYSTEM_TASK:> Update info about a network interface according <END_TASK> <USER_TASK:> Description: def update(self, data): """Update info about a network interface according to a given dictionary. Such data is provided by get_windows_if_list """
self.data = data self.name = data['name'] self.description = data['description'] self.win_index = data['win_index'] self.guid = data['guid'] self.mac = data['mac'] self.ipv4_metric = data['ipv4_metric'] self.ipv6_metric = data['ipv6_metric'] self....
<SYSTEM_TASK:> Returns True if the interface is in monitor mode. <END_TASK> <USER_TASK:> Description: def ismonitor(self): """Returns True if the interface is in monitor mode. Only available with Npcap."""
if self.cache_mode is not None: return self.cache_mode try: res = (self.mode() == "monitor") self.cache_mode = res return res except Scapy_Exception: return False
<SYSTEM_TASK:> Return the first pcap device name for a given Windows <END_TASK> <USER_TASK:> Description: def dev_from_name(self, name): """Return the first pcap device name for a given Windows device name. """
try: return next(iface for iface in six.itervalues(self) if (iface.name == name or iface.description == name)) except (StopIteration, RuntimeError): raise ValueError("Unknown network interface %r" % name)
<SYSTEM_TASK:> Returns the right class for a given NTP packet. <END_TASK> <USER_TASK:> Description: def _ntp_dispatcher(payload): """ Returns the right class for a given NTP packet. """
# By default, calling NTP() will build a NTP packet as defined in RFC 5905 # (see the code of NTPHeader). Use NTPHeader for extension fields and MAC. if payload is None: return NTPHeader else: length = len(payload) if length >= _NTP_PACKET_MIN_SIZE: first_byte = orb(...
<SYSTEM_TASK:> Check that the payload is long enough to build a NTP packet. <END_TASK> <USER_TASK:> Description: def pre_dissect(self, s): """ Check that the payload is long enough to build a NTP packet. """
length = len(s) if length < _NTP_PACKET_MIN_SIZE: err = " ({}".format(length) + " is < _NTP_PACKET_MIN_SIZE " err += "({})).".format(_NTP_PACKET_MIN_SIZE) raise _NTPInvalidDataException(err) return s
<SYSTEM_TASK:> There is actually only one key, the CLIENT-READ-KEY or -WRITE-KEY. <END_TASK> <USER_TASK:> Description: def sslv2_derive_keys(self, key_material): """ There is actually only one key, the CLIENT-READ-KEY or -WRITE-KEY. Note that skip_first is opposite from the one with SSLv3 deriv...
skip_first = True if ((self.connection_end == "client" and self.row == "read") or (self.connection_end == "server" and self.row == "write")): skip_first = False cipher_alg = self.ciphersuite.cipher_alg start = 0 if skip_first: start += c...
<SYSTEM_TASK:> This is used mostly as a way to keep the cipher state and the seq_num. <END_TASK> <USER_TASK:> Description: def snapshot(self): """ This is used mostly as a way to keep the cipher state and the seq_num. """
snap = connState(connection_end=self.connection_end, read_or_write=self.row, seq_num=self.seq_num, compression_alg=type(self.compression), ciphersuite=type(self.ciphersuite), tls_version...
<SYSTEM_TASK:> Ciphers key and IV are updated accordingly for 0-RTT data. <END_TASK> <USER_TASK:> Description: def compute_tls13_early_secrets(self): """ Ciphers key and IV are updated accordingly for 0-RTT data. self.handshake_messages should be ClientHello only. """
# we use the prcs rather than the pwcs in a totally arbitrary way if self.prcs is None: # too soon return hkdf = self.prcs.hkdf self.tls13_early_secret = hkdf.extract(None, self.tls13_psk_secret) bk = hkdf...
<SYSTEM_TASK:> Ciphers key and IV are updated accordingly for Handshake data. <END_TASK> <USER_TASK:> Description: def compute_tls13_handshake_secrets(self): """ Ciphers key and IV are updated accordingly for Handshake data. self.handshake_messages should be ClientHello...ServerHello. ""...
if self.tls13_early_secret is None: warning("No early secret. This is abnormal.") hkdf = self.prcs.hkdf self.tls13_handshake_secret = hkdf.extract(self.tls13_early_secret, self.tls13_dhe_secret) chts = hkdf.derive_secret(...
<SYSTEM_TASK:> Ciphers key and IV are updated accordingly for Application data. <END_TASK> <USER_TASK:> Description: def compute_tls13_traffic_secrets(self): """ Ciphers key and IV are updated accordingly for Application data. self.handshake_messages should be ClientHello...ServerFinished. ...
hkdf = self.prcs.hkdf self.tls13_master_secret = hkdf.extract(self.tls13_handshake_secret, None) cts0 = hkdf.derive_secret(self.tls13_master_secret, b"client application traffic secret", ...
<SYSTEM_TASK:> self.handshake_messages should be ClientHello...ClientFinished. <END_TASK> <USER_TASK:> Description: def compute_tls13_resumption_secret(self): """ self.handshake_messages should be ClientHello...ClientFinished. """
if self.connection_end == "server": hkdf = self.prcs.hkdf elif self.connection_end == "client": hkdf = self.pwcs.hkdf rs = hkdf.derive_secret(self.tls13_master_secret, b"resumption master secret", b"".join(s...
<SYSTEM_TASK:> Ciphers key and IV are updated accordingly. <END_TASK> <USER_TASK:> Description: def compute_tls13_next_traffic_secrets(self): """ Ciphers key and IV are updated accordingly. """
hkdf = self.prcs.hkdf hl = hkdf.hash.digest_size cts = self.tls13_derived_secrets["client_traffic_secrets"] ctsN = cts[-1] ctsN_1 = hkdf.expand_label(ctsN, "application traffic secret", "", hl) cts.append(ctsN_1) stsN_1 = hkdf.expand_label(ctsN, "application tr...
<SYSTEM_TASK:> Guess the correct LLS class for a given payload <END_TASK> <USER_TASK:> Description: def _LLSGuessPayloadClass(p, **kargs): """ Guess the correct LLS class for a given payload """
cls = conf.raw_layer if len(p) >= 3: typ = struct.unpack("!H", p[0:2])[0] clsname = _OSPF_LLSclasses.get(typ, "LLS_Generic_TLV") cls = globals()[clsname] return cls(p, **kargs)
<SYSTEM_TASK:> Guess the correct OSPFv3 LSA class for a given payload <END_TASK> <USER_TASK:> Description: def _OSPFv3_LSAGuessPayloadClass(p, **kargs): """ Guess the correct OSPFv3 LSA class for a given payload """
cls = conf.raw_layer if len(p) >= 6: typ = struct.unpack("!H", p[2:4])[0] clsname = _OSPFv3_LSclasses.get(typ, "Raw") cls = globals()[clsname] return cls(p, **kargs)
<SYSTEM_TASK:> Return MAC address corresponding to a given IP address <END_TASK> <USER_TASK:> Description: def getmacbyip(ip, chainCC=0): """Return MAC address corresponding to a given IP address"""
if isinstance(ip, Net): ip = next(iter(ip)) ip = inet_ntoa(inet_aton(ip or "0.0.0.0")) tmp = [orb(e) for e in inet_aton(ip)] if (tmp[0] & 0xf0) == 0xe0: # mcast @ return "01:00:5e:%.2x:%.2x:%.2x" % (tmp[1] & 0x7f, tmp[2], tmp[3]) iff, _, gw = conf.route.route(ip) if ((iff == co...
<SYSTEM_TASK:> Try to guess if target is in Promisc mode. The target is provided by its ip. <END_TASK> <USER_TASK:> Description: def is_promisc(ip, fake_bcast="ff:ff:00:00:00:00", **kargs): """Try to guess if target is in Promisc mode. The target is provided by its ip."""
# noqa: E501 responses = srp1(Ether(dst=fake_bcast) / ARP(op="who-has", pdst=ip), type=ETH_P_ARP, iface_hint=ip, timeout=1, verbose=0, **kargs) # noqa: E501 return responses is not None
<SYSTEM_TASK:> This function decompresses a string s, starting <END_TASK> <USER_TASK:> Description: def dns_get_str(s, pointer=0, pkt=None, _fullpacket=False): """This function decompresses a string s, starting from the given pointer. :param s: the string to decompress :param pointer: first pointer on ...
# The _fullpacket parameter is reserved for scapy. It indicates # that the string provided is the full dns packet, and thus # will be the same than pkt._orig_str. The "Cannot decompress" # error will not be prompted if True. max_length = len(s) # The result = the extracted name name = b"" ...
<SYSTEM_TASK:> Encodes a bytes string into the DNS format <END_TASK> <USER_TASK:> Description: def dns_encode(x, check_built=False): """Encodes a bytes string into the DNS format :param x: the string :param check_built: detect already-built strings and ignore them :returns: the encoded bytes string ...
if not x or x == b".": return b"\x00" if check_built and b"." not in x and ( orb(x[-1]) == 0 or (orb(x[-2]) & 0xc0) == 0xc0 ): # The value has already been processed. Do not process it again return x # Truncate chunks that cannot be encoded (more than 63 bytes..) x...
<SYSTEM_TASK:> This function compresses a DNS packet according to compression rules. <END_TASK> <USER_TASK:> Description: def dns_compress(pkt): """This function compresses a DNS packet according to compression rules. """
if DNS not in pkt: raise Scapy_Exception("Can only compress DNS layers") pkt = pkt.copy() dns_pkt = pkt.getlayer(DNS) build_pkt = raw(dns_pkt) def field_gen(dns_pkt): """Iterates through all DNS strings that can be compressed""" for lay in [dns_pkt.qd, dns_pkt.an, dns_pkt.n...
<SYSTEM_TASK:> Unpack the internal representation. <END_TASK> <USER_TASK:> Description: def _convert_seconds(self, packed_seconds): """Unpack the internal representation."""
seconds = struct.unpack("!H", packed_seconds[:2])[0] seconds += struct.unpack("!I", packed_seconds[2:])[0] return seconds
<SYSTEM_TASK:> Convert the number of seconds since 1-Jan-70 UTC to the packed <END_TASK> <USER_TASK:> Description: def h2i(self, pkt, seconds): """Convert the number of seconds since 1-Jan-70 UTC to the packed representation."""
if seconds is None: seconds = 0 tmp_short = (seconds >> 32) & 0xFFFF tmp_int = seconds & 0xFFFFFFFF return struct.pack("!HI", tmp_short, tmp_int)
<SYSTEM_TASK:> Convert the internal representation to a nice one using the RFC <END_TASK> <USER_TASK:> Description: def i2repr(self, pkt, packed_seconds): """Convert the internal representation to a nice one using the RFC format."""
time_struct = time.gmtime(self._convert_seconds(packed_seconds)) return time.strftime("%a %b %d %H:%M:%S %Y", time_struct)
<SYSTEM_TASK:> Sends and receive an ICMPv6 Neighbor Solicitation message <END_TASK> <USER_TASK:> Description: def neighsol(addr, src, iface, timeout=1, chainCC=0): """Sends and receive an ICMPv6 Neighbor Solicitation message This function sends an ICMPv6 Neighbor Solicitation message to get the MAC address...
nsma = in6_getnsma(inet_pton(socket.AF_INET6, addr)) d = inet_ntop(socket.AF_INET6, nsma) dm = in6_getnsmac(nsma) p = Ether(dst=dm) / IPv6(dst=d, src=src, hlim=255) p /= ICMPv6ND_NS(tgt=addr) p /= ICMPv6NDOptSrcLLAddr(lladdr=get_if_hwaddr(iface)) res = srp1(p, type=ETH_P_IPV6, iface=iface,...
<SYSTEM_TASK:> Returns the MAC address corresponding to an IPv6 address <END_TASK> <USER_TASK:> Description: def getmacbyip6(ip6, chainCC=0): """Returns the MAC address corresponding to an IPv6 address neighborCache.get() method is used on instantiated neighbor cache. Resolution mechanism is described in a...
if isinstance(ip6, Net6): ip6 = str(ip6) if in6_ismaddr(ip6): # Multicast mac = in6_getnsmac(inet_pton(socket.AF_INET6, ip6)) return mac iff, a, nh = conf.route6.route(ip6) if iff == scapy.consts.LOOPBACK_INTERFACE: return "ff:ff:ff:ff:ff:ff" if nh != '::': ...
<SYSTEM_TASK:> Internal generic helper accepting a specific callback as first argument, <END_TASK> <USER_TASK:> Description: def _NDP_Attack_DAD_DoS(reply_callback, iface=None, mac_src_filter=None, tgt_filter=None, reply_mac=None): """ Internal generic helper accepting a specific callbac...
def is_request(req, mac_src_filter, tgt_filter): """ Check if packet req is a request """ # Those simple checks are based on Section 5.4.2 of RFC 4862 if not (Ether in req and IPv6 in req and ICMPv6ND_NS in req): return 0 # Get and compare the MAC addr...
<SYSTEM_TASK:> Perform the DAD DoS attack using NS described in section 4.1.3 of RFC <END_TASK> <USER_TASK:> Description: def NDP_Attack_DAD_DoS_via_NS(iface=None, mac_src_filter=None, tgt_filter=None, reply_mac=None): """ Perform the DAD DoS attack using NS described in section 4....
def ns_reply_callback(req, reply_mac, iface): """ Callback that reply to a NS by sending a similar NS """ # Let's build a reply and send it mac = req[Ether].src dst = req[IPv6].dst tgt = req[ICMPv6ND_NS].tgt rep = Ether(src=reply_mac) / IPv6(src="::...
<SYSTEM_TASK:> Used to select the L2 address <END_TASK> <USER_TASK:> Description: def route(self): """Used to select the L2 address"""
dst = self.dst if isinstance(dst, Gen): dst = next(iter(dst)) return conf.route6.route(dst)
<SYSTEM_TASK:> Compute the 'sources_number' field when needed <END_TASK> <USER_TASK:> Description: def post_build(self, packet, payload): """Compute the 'sources_number' field when needed"""
if self.sources_number is None: srcnum = struct.pack("!H", len(self.sources)) packet = packet[:26] + srcnum + packet[28:] return _ICMPv6.post_build(self, packet, payload)
<SYSTEM_TASK:> Compute the 'records_number' field when needed <END_TASK> <USER_TASK:> Description: def post_build(self, packet, payload): """Compute the 'records_number' field when needed"""
if self.records_number is None: recnum = struct.pack("!H", len(self.records)) packet = packet[:6] + recnum + packet[8:] return _ICMPv6.post_build(self, packet, payload)
<SYSTEM_TASK:> Add the endianness to the format <END_TASK> <USER_TASK:> Description: def set_endianess(self, pkt): """Add the endianness to the format"""
end = self.endianess_from(pkt) if isinstance(end, str) and end: if isinstance(self.fld, UUIDField): self.fld.uuid_fmt = (UUIDField.FORMAT_LE if end == '<' else UUIDField.FORMAT_BE) else: # fld.fmt should always...
<SYSTEM_TASK:> add the field with endianness to the buffer <END_TASK> <USER_TASK:> Description: def addfield(self, pkt, buf, val): """add the field with endianness to the buffer"""
self.set_endianess(pkt) return self.fld.addfield(pkt, buf, val)
<SYSTEM_TASK:> dispatch_hook to choose among different registered payloads <END_TASK> <USER_TASK:> Description: def dispatch_hook(cls, _pkt, _underlayer=None, *args, **kargs): """dispatch_hook to choose among different registered payloads"""
for klass in cls._payload_class: if hasattr(klass, "can_handle") and \ klass.can_handle(_pkt, _underlayer): return klass print("DCE/RPC payload class not found or undefined (using Raw)") return Raw
<SYSTEM_TASK:> _parse_multi_byte parses x as a multibyte representation to get the <END_TASK> <USER_TASK:> Description: def _parse_multi_byte(self, s): # type: (str) -> int """ _parse_multi_byte parses x as a multibyte representation to get the int value of this AbstractUVarIntField. ...
assert(len(s) >= 2) tmp_len = len(s) value = 0 i = 1 byte = orb(s[i]) # For CPU sake, stops at an arbitrary large number! max_value = 1 << 64 # As long as the MSG is set, an another byte must be read while byte & 0x80: value += (byt...
<SYSTEM_TASK:> Computes the value of this field based on the provided packet and <END_TASK> <USER_TASK:> Description: def _compute_value(self, pkt): # type: (packet.Packet) -> int """ Computes the value of this field based on the provided packet and the length_of field and the adjust callback ...
fld, fval = pkt.getfield_and_val(self._length_of) val = fld.i2len(pkt, fval) ret = self._adjust(val) assert(ret >= 0) return ret
<SYSTEM_TASK:> huffman_encode_char assumes that the static_huffman_tree was <END_TASK> <USER_TASK:> Description: def _huffman_encode_char(cls, c): # type: (Union[str, EOS]) -> Tuple[int, int] """ huffman_encode_char assumes that the static_huffman_tree was previously initialized @param ...
if isinstance(c, EOS): return cls.static_huffman_code[-1] else: assert(isinstance(c, int) or len(c) == 1) return cls.static_huffman_code[orb(c)]
<SYSTEM_TASK:> huffman_encode returns the bitstring and the bitlength of the <END_TASK> <USER_TASK:> Description: def huffman_encode(cls, s): # type: (str) -> Tuple[int, int] """ huffman_encode returns the bitstring and the bitlength of the bitstring representing the string provided as a paramet...
i = 0 ibl = 0 for c in s: val, bl = cls._huffman_encode_char(c) i = (i << bl) + val ibl += bl padlen = 8 - (ibl % 8) if padlen != 8: val, bl = cls._huffman_encode_char(EOS()) i = (i << padlen) + (val >> (bl - padlen)) ...
<SYSTEM_TASK:> huffman_decode decodes the bitstring provided as parameters. <END_TASK> <USER_TASK:> Description: def huffman_decode(cls, i, ibl): # type: (int, int) -> str """ huffman_decode decodes the bitstring provided as parameters. @param int i: the bitstring to decode @param int i...
assert(i >= 0) assert(ibl >= 0) if isinstance(cls.static_huffman_tree, type(None)): cls.huffman_compute_decode_tree() assert(not isinstance(cls.static_huffman_tree, type(None))) s = [] j = 0 interrupted = False cur = cls.static_huffman_tree ...
<SYSTEM_TASK:> self_build is overridden because type and len are determined at <END_TASK> <USER_TASK:> Description: def self_build(self, field_pos_list=None): # type: (Any) -> str """self_build is overridden because type and len are determined at build time, based on the "data" field internal ty...
if self.getfieldval('type') is None: self.type = 1 if isinstance(self.getfieldval('data'), HPackZString) else 0 # noqa: E501 return super(HPackHdrString, self).self_build(field_pos_list)
<SYSTEM_TASK:> dispatch_hook returns the subclass of HPackHeaders that must be used <END_TASK> <USER_TASK:> Description: def dispatch_hook(cls, s=None, *_args, **_kwds): # type: (Optional[str], *Any, **Any) -> base_classes.Packet_metaclass """dispatch_hook returns the subclass of HPackHeaders that must ...
if s is None: return config.conf.raw_layer fb = orb(s[0]) if fb & 0x80 != 0: return HPackIndexedHdr if fb & 0x40 != 0: return HPackLitHdrFldWithIncrIndexing if fb & 0x20 != 0: return HPackDynamicSizeUpdate return HPackLitHd...
<SYSTEM_TASK:> get_data_len computes the length of the data field <END_TASK> <USER_TASK:> Description: def get_data_len(self): # type: () -> int """ get_data_len computes the length of the data field To do this computation, the length of the padlen field and the actual padding is subtra...
padding_len = self.getfieldval('padlen') fld, fval = self.getfield_and_val('padlen') padding_len_len = fld.i2len(self, fval) ret = self.s_len - padding_len_len - padding_len assert(ret >= 0) return ret
<SYSTEM_TASK:> _reduce_dynamic_table evicts entries from the dynamic table until it <END_TASK> <USER_TASK:> Description: def _reduce_dynamic_table(self, new_entry_size=0): # type: (int) -> None """_reduce_dynamic_table evicts entries from the dynamic table until it fits in less than the current ...
assert(new_entry_size >= 0) cur_sz = len(self) dyn_tbl_sz = len(self._dynamic_table) while dyn_tbl_sz > 0 and cur_sz + new_entry_size > self._dynamic_table_max_size: # noqa: E501 last_elmt_sz = len(self._dynamic_table[-1]) self._dynamic_table.pop() d...
<SYSTEM_TASK:> register adds to this table the instances of <END_TASK> <USER_TASK:> Description: def register(self, hdrs): # type: (Union[HPackLitHdrFldWithIncrIndexing, H2Frame, List[HPackHeaders]]) -> None # noqa: E501 """register adds to this table the instances of HPackLitHdrFldWithIncrInde...
if isinstance(hdrs, H2Frame): hdrs = [hdr for hdr in hdrs.payload.hdrs if isinstance(hdr, HPackLitHdrFldWithIncrIndexing)] # noqa: E501 elif isinstance(hdrs, HPackLitHdrFldWithIncrIndexing): hdrs = [hdrs] else: hdrs = [hdr for hdr in hdrs if isinstance(hdr, ...
<SYSTEM_TASK:> get_idx_by_name returns the index of a matching registered header <END_TASK> <USER_TASK:> Description: def get_idx_by_name(self, name): # type: (str) -> Optional[int] """ get_idx_by_name returns the index of a matching registered header This implementation will prefer returning a...
name = name.lower() for key, val in six.iteritems(type(self)._static_entries): if val.name() == name: return key for idx, val in enumerate(self._dynamic_table): if val.name() == name: return type(self)._static_entries_last_idx + idx + 1 ...
<SYSTEM_TASK:> gen_txt_repr returns a "textual" representation of the provided <END_TASK> <USER_TASK:> Description: def gen_txt_repr(self, hdrs, register=True): # type: (Union[H2Frame, List[HPackHeaders]], Optional[bool]) -> str """ gen_txt_repr returns a "textual" representation of the provided ...
lst = [] if isinstance(hdrs, H2Frame): hdrs = hdrs.payload.hdrs for hdr in hdrs: try: if isinstance(hdr, HPackIndexedHdr): lst.append('{}'.format(self[hdr.index])) elif isinstance(hdr, ( HPackLitHdr...
<SYSTEM_TASK:> Craft an AVP based on its id and optional parameter fields <END_TASK> <USER_TASK:> Description: def AVP(avpId, **fields): """ Craft an AVP based on its id and optional parameter fields"""
val = None classType = AVP_Unknown if isinstance(avpId, str): try: for vnd in AvpDefDict: for code in AvpDefDict[vnd]: val = AvpDefDict[vnd][code] if val[0][:len( avpId)] == avpId: # A prefix of the ful...
<SYSTEM_TASK:> Given a Packet instance `pkt` and the value `val` to be set, <END_TASK> <USER_TASK:> Description: def _find_fld_pkt_val(self, pkt, val): """Given a Packet instance `pkt` and the value `val` to be set, returns the Field subclass to be used, and the updated `val` if necessary. """
fld = self._iterate_fields_cond(pkt, val, True) # Default ? (in this case, let's make sure it's up-do-date) dflts_pkt = pkt.default_fields if val == dflts_pkt[self.name] and self.name not in pkt.fields: dflts_pkt[self.name] = fld.default val = fld.default ...
<SYSTEM_TASK:> Returns the Field subclass to be used, depending on the Packet <END_TASK> <USER_TASK:> Description: def _find_fld(self): """Returns the Field subclass to be used, depending on the Packet instance, or the default subclass. DEV: since the Packet instance is not provided, we have to use a hack to g...
# Hack to preserve current Scapy API # See https://stackoverflow.com/a/7272464/3223422 frame = inspect.currentframe().f_back.f_back while frame is not None: try: pkt = frame.f_locals['self'] except KeyError: pass else: ...
<SYSTEM_TASK:> Checks .uuid_fmt, and raises an exception if it is not valid. <END_TASK> <USER_TASK:> Description: def _check_uuid_fmt(self): """Checks .uuid_fmt, and raises an exception if it is not valid."""
if self.uuid_fmt not in UUIDField.FORMATS: raise FieldValueRangeException( "Unsupported uuid_fmt ({})".format(self.uuid_fmt))
<SYSTEM_TASK:> We need to parse the padding and type as soon as possible, <END_TASK> <USER_TASK:> Description: def pre_dissect(self, s): """ We need to parse the padding and type as soon as possible, else we won't be able to parse the message list... """
if len(s) < 1: raise Exception("Invalid InnerPlaintext (too short).") tmp_len = len(s) - 1 if s[-1] != b"\x00": msg_len = tmp_len else: n = 1 while s[-n] != b"\x00" and n < tmp_len: n += 1 msg_len = tmp_len - n...
<SYSTEM_TASK:> Decrypt, verify and decompress the message. <END_TASK> <USER_TASK:> Description: def pre_dissect(self, s): """ Decrypt, verify and decompress the message. """
if len(s) < 5: raise Exception("Invalid record: header is too short.") if isinstance(self.tls_session.rcs.cipher, Cipher_NULL): self.deciphered_len = None return s else: msglen = struct.unpack('!H', s[3:5])[0] hdr, efrag, r = s[:5], s...
<SYSTEM_TASK:> Build a TKIP header for IV @iv and mac @mac, and encrypt @data <END_TASK> <USER_TASK:> Description: def build_TKIP_payload(data, iv, mac, tk): """Build a TKIP header for IV @iv and mac @mac, and encrypt @data based on temporal key @tk """
TSC5, TSC4, TSC3, TSC2, TSC1, TSC0 = ( (iv >> 40) & 0xFF, (iv >> 32) & 0xFF, (iv >> 24) & 0xFF, (iv >> 16) & 0xFF, (iv >> 8) & 0xFF, iv & 0xFF ) bitfield = 1 << 5 # Extended IV TKIP_hdr = chb(TSC1) + chb((TSC1 | 0x20) & 0x7f) + chb(TSC0) + chb(bitfield) ...
<SYSTEM_TASK:> Compute and return the data with its MIC and ICV <END_TASK> <USER_TASK:> Description: def build_MIC_ICV(data, mic_key, source, dest): """Compute and return the data with its MIC and ICV"""
# DATA - MIC(DA - SA - Priority=0 - 0 - 0 - 0 - DATA) - ICV # 802.11i p.47 sa = mac2str(source) # Source MAC da = mac2str(dest) # Dest MAC MIC = michael(mic_key, da + sa + b"\x00" + b"\x00" * 3 + data) ICV = pack("<I", crc32(data + MIC) & 0xFFFFFFFF) return data + MIC + ICV
<SYSTEM_TASK:> Least Common Multiple between 2 integers. <END_TASK> <USER_TASK:> Description: def _lcm(a, b): """ Least Common Multiple between 2 integers. """
if a == 0 or b == 0: return 0 else: return abs(a * b) // gcd(a, b)
<SYSTEM_TASK:> Encrypt an ESP packet <END_TASK> <USER_TASK:> Description: def encrypt(self, sa, esp, key): """ Encrypt an ESP packet @param sa: the SecurityAssociation associated with the ESP packet. @param esp: an unencrypted _ESPPlain packet with valid padding @param key: ...
data = esp.data_for_encryption() if self.cipher: mode_iv = self._format_mode_iv(algo=self, sa=sa, iv=esp.iv) cipher = self.new_cipher(key, mode_iv) encryptor = cipher.encryptor() if self.is_aead: aad = struct.pack('!LL', esp.spi, esp.seq...
<SYSTEM_TASK:> Check that the key length is valid. <END_TASK> <USER_TASK:> Description: def check_key(self, key): """ Check that the key length is valid. @param key: a byte string """
if self.key_size and len(key) not in self.key_size: raise TypeError('invalid key size %s, must be one of %s' % (len(key), self.key_size))
<SYSTEM_TASK:> Increment the explicit nonce while avoiding any overflow. <END_TASK> <USER_TASK:> Description: def _update_nonce_explicit(self): """ Increment the explicit nonce while avoiding any overflow. """
ne = self.nonce_explicit + 1 self.nonce_explicit = ne % 2**(self.nonce_explicit_len * 8)
<SYSTEM_TASK:> Encrypt the data, and append the computed authentication code. <END_TASK> <USER_TASK:> Description: def auth_encrypt(self, P, A, seq_num): """ Encrypt the data, and append the computed authentication code. TLS 1.3 does not use additional data, but we leave this option to the ...
if False in six.itervalues(self.ready): raise CipherError(P, A) if hasattr(self, "pc_cls"): self._cipher.mode._tag = None self._cipher.mode._initialization_vector = self._get_nonce(seq_num) encryptor = self._cipher.encryptor() encryptor.authe...
<SYSTEM_TASK:> Return the 3-tuple made of the Key Exchange Algorithm class, the Cipher <END_TASK> <USER_TASK:> Description: def get_algs_from_ciphersuite_name(ciphersuite_name): """ Return the 3-tuple made of the Key Exchange Algorithm class, the Cipher class and the HMAC class, through the parsing of the c...
tls1_3 = False if ciphersuite_name.startswith("TLS"): s = ciphersuite_name[4:] if s.endswith("CCM") or s.endswith("CCM_8"): kx_name, s = s.split("_WITH_") kx_alg = _tls_kx_algs.get(kx_name) hash_alg = _tls_hash_algs.get("SHA256") cipher_alg = _tl...
<SYSTEM_TASK:> From a list of proposed ciphersuites, this function returns a list of <END_TASK> <USER_TASK:> Description: def get_usable_ciphersuites(l, kx): """ From a list of proposed ciphersuites, this function returns a list of usable cipher suites, i.e. for which key exchange, cipher and hash algor...
res = [] for c in l: if c in _tls_cipher_suites_cls: ciph = _tls_cipher_suites_cls[c] if ciph.usable: # XXX select among RSA and ECDSA cipher suites # according to the key(s) the server was given if ciph.kx_alg.anonymous or kx in c...
<SYSTEM_TASK:> Identify IP id values classes in a list of packets <END_TASK> <USER_TASK:> Description: def IPID_count(lst, funcID=lambda x: x[1].id, funcpres=lambda x: x[1].summary()): # noqa: E501 """Identify IP id values classes in a list of packets lst: a list of packets funcID: a function that returns ...
idlst = [funcID(e) for e in lst] idlst.sort() classes = [idlst[0]] classes += [t[1] for t in zip(idlst[:-1], idlst[1:]) if abs(t[0] - t[1]) > 50] # noqa: E501 lst = [(funcID(x), funcpres(x)) for x in lst] lst.sort() print("Probably %i classes:" % len(classes), classes) for id, pr in ls...
<SYSTEM_TASK:> Returns ttl or hlim, depending on the IP version <END_TASK> <USER_TASK:> Description: def _ttl(self): """Returns ttl or hlim, depending on the IP version"""
return self.hlim if isinstance(self, scapy.layers.inet6.IPv6) else self.ttl
<SYSTEM_TASK:> Called to explicitly fixup the packet according to the IGMP RFC <END_TASK> <USER_TASK:> Description: def igmpize(self): """Called to explicitly fixup the packet according to the IGMP RFC The rules are: General: 1. the Max Response time is meaningful only in Membershi...
gaddr = self.gaddr if hasattr(self, "gaddr") and self.gaddr else "0.0.0.0" # noqa: E501 underlayer = self.underlayer if self.type not in [0x11, 0x30]: # General Rule 1 # noqa: E501 self.mrcode = 0 if isinstance(underlayer, IP): if ...
<SYSTEM_TASK:> Returns the right class for a given BGP message. <END_TASK> <USER_TASK:> Description: def _bgp_dispatcher(payload): """ Returns the right class for a given BGP message. """
cls = conf.raw_layer # By default, calling BGP() will build a BGPHeader. if payload is None: cls = _get_cls("BGPHeader", conf.raw_layer) else: if len(payload) >= _BGP_HEADER_SIZE and\ payload[:16] == _BGP_HEADER_MARKER: # Get BGP message type ...
<SYSTEM_TASK:> Returns the right class for a given BGP capability. <END_TASK> <USER_TASK:> Description: def _bgp_capability_dispatcher(payload): """ Returns the right class for a given BGP capability. """
cls = _capabilities_registry["BGPCapGeneric"] # By default, calling BGPCapability() will build a "generic" capability. if payload is None: cls = _capabilities_registry["BGPCapGeneric"] else: length = len(payload) if length >= _BGP_CAPABILITY_MIN_SIZE: code = orb(p...
<SYSTEM_TASK:> This will set the ByteField 'length' to the correct value. <END_TASK> <USER_TASK:> Description: def post_build(self, pkt, pay): """ This will set the ByteField 'length' to the correct value. """
if self.length is None: pkt = pkt[:4] + chb(len(pay)) + pkt[5:] return pkt + pay
<SYSTEM_TASK:> ISOTP encodes the frame type in the first nibble of a frame. <END_TASK> <USER_TASK:> Description: def guess_payload_class(self, payload): """ ISOTP encodes the frame type in the first nibble of a frame. """
t = (orb(payload[0]) & 0xf0) >> 4 if t == 0: return ISOTP_SF elif t == 1: return ISOTP_FF elif t == 2: return ISOTP_CF else: return ISOTP_FC
<SYSTEM_TASK:> Attempt to feed an incoming CAN frame into the state machine <END_TASK> <USER_TASK:> Description: def feed(self, can): """Attempt to feed an incoming CAN frame into the state machine"""
if not isinstance(can, CAN): raise Scapy_Exception("argument is not a CAN frame") identifier = can.identifier data = bytes(can.data) if len(data) > 1 and self.use_ext_addr is not True: self._try_feed(identifier, None, data) if len(data) > 2 and self.use_...
<SYSTEM_TASK:> Begin the transmission of message p. This method returns after <END_TASK> <USER_TASK:> Description: def begin_send(self, p): """Begin the transmission of message p. This method returns after sending the first frame. If multiple frames are necessary to send the message, this socket...
if hasattr(p, "sent_time"): p.sent_time = time.time() return self.outs.begin_send(bytes(p))
<SYSTEM_TASK:> Receive a complete ISOTP message, blocking until a message is <END_TASK> <USER_TASK:> Description: def recv_with_timeout(self, timeout=1): """Receive a complete ISOTP message, blocking until a message is received or the specified timeout is reached. If timeout is 0, then this func...
msg = self.ins.recv(timeout) t = time.time() if msg is None: raise Scapy_Exception("Timeout") return self.basecls, msg, t
<SYSTEM_TASK:> Receive a complete ISOTP message, blocking until a message is <END_TASK> <USER_TASK:> Description: def recv_raw(self, x=0xffff): """Receive a complete ISOTP message, blocking until a message is received or the specified timeout is reached. If self.timeout is 0, then this function ...
msg = self.ins.recv() t = time.time() return self.basecls, msg, t
<SYSTEM_TASK:> Call 'callback' in 'timeout' seconds, unless cancelled. <END_TASK> <USER_TASK:> Description: def set_timeout(self, timeout, callback): """Call 'callback' in 'timeout' seconds, unless cancelled."""
if not self._ready_sem.acquire(False): raise Scapy_Exception("Timer was already started") self._callback = callback self._timeout = timeout self._cancelled.clear() self._busy_sem.release()
<SYSTEM_TASK:> Stop the timer without executing the callback. <END_TASK> <USER_TASK:> Description: def cancel(self): """Stop the timer without executing the callback."""
self._cancelled.set() if not self._dead: self._ready_sem.acquire() self._ready_sem.release()
<SYSTEM_TASK:> Stop the thread, making this object unusable. <END_TASK> <USER_TASK:> Description: def stop(self): """Stop the thread, making this object unusable."""
if not self._dead: self._killed = True self._cancelled.set() self._busy_sem.release() self.join() if not self._ready_sem.acquire(False): warning("ISOTP Timer thread may not have stopped " "correctly")
<SYSTEM_TASK:> Method called every time the rx_timer times out, due to the peer not <END_TASK> <USER_TASK:> Description: def _rx_timer_handler(self): """Method called every time the rx_timer times out, due to the peer not sending a consecutive frame within the expected time window"""
with self.rx_mutex: if self.rx_state == ISOTP_WAIT_DATA: # we did not get new data frames in time. # reset rx state self.rx_state = ISOTP_IDLE warning("RX state was reset due to timeout")
<SYSTEM_TASK:> Function that must be called every time a CAN frame is received, to <END_TASK> <USER_TASK:> Description: def on_recv(self, cf): """Function that must be called every time a CAN frame is received, to advance the state machine."""
data = bytes(cf.data) if len(data) < 2: return ae = 0 if self.extended_rx_addr is not None: ae = 1 if len(data) < 3: return if six.indexbytes(data, 0) != self.extended_rx_addr: return n_pci = six...
<SYSTEM_TASK:> Process a received 'Flow Control' frame <END_TASK> <USER_TASK:> Description: def _recv_fc(self, data): """Process a received 'Flow Control' frame"""
if (self.tx_state != ISOTP_WAIT_FC and self.tx_state != ISOTP_WAIT_FIRST_FC): return 0 self.tx_timer.cancel() if len(data) < 3: self.tx_state = ISOTP_IDLE self.tx_exception = "CF frame discarded because it was too short" self.tx_...
<SYSTEM_TASK:> Process a received 'Single Frame' frame <END_TASK> <USER_TASK:> Description: def _recv_sf(self, data): """Process a received 'Single Frame' frame"""
self.rx_timer.cancel() if self.rx_state != ISOTP_IDLE: warning("RX state was reset because single frame was received") self.rx_state = ISOTP_IDLE length = six.indexbytes(data, 0) & 0xf if len(data) - 1 < length: return 1 msg = data[1:1 + len...
<SYSTEM_TASK:> Process a received 'Consecutive Frame' frame <END_TASK> <USER_TASK:> Description: def _recv_cf(self, data): """Process a received 'Consecutive Frame' frame"""
if self.rx_state != ISOTP_WAIT_DATA: return 0 self.rx_timer.cancel() # CFs are never longer than the FF if len(data) > self.rx_ll_dl: return 1 # CFs have usually the LL_DL length if len(data) < self.rx_ll_dl: # this is only allowed ...
<SYSTEM_TASK:> Begins sending an ISOTP message. This method does not block. <END_TASK> <USER_TASK:> Description: def begin_send(self, x): """Begins sending an ISOTP message. This method does not block."""
with self.tx_mutex: if self.tx_state != ISOTP_IDLE: raise Scapy_Exception("Socket is already sending, retry later") self.tx_done.clear() self.tx_exception = None self.tx_state = ISOTP_SENDING length = len(x) if length > I...
<SYSTEM_TASK:> Send an ISOTP frame and block until the message is sent or an error <END_TASK> <USER_TASK:> Description: def send(self, p): """Send an ISOTP frame and block until the message is sent or an error happens."""
with self.send_mutex: self.begin_send(p) # Wait until the tx callback is called self.tx_done.wait() if self.tx_exception is not None: raise Scapy_Exception(self.tx_exception) return
<SYSTEM_TASK:> Receive an ISOTP frame, blocking if none is available in the buffer <END_TASK> <USER_TASK:> Description: def recv(self, timeout=None): """Receive an ISOTP frame, blocking if none is available in the buffer for at most 'timeout' seconds."""
try: return self.rx_queue.get(timeout is None or timeout > 0, timeout) except queue.Empty: return None
<SYSTEM_TASK:> Returns the right parameter set class. <END_TASK> <USER_TASK:> Description: def dispatch_hook(cls, _pkt=None, *args, **kargs): """ Returns the right parameter set class. """
cls = conf.raw_layer if _pkt is not None: ptype = orb(_pkt[0]) return globals().get(_param_set_cls.get(ptype), conf.raw_layer) return cls
<SYSTEM_TASK:> dissect the IPv6 package compressed into this IPHC packet. <END_TASK> <USER_TASK:> Description: def post_dissect(self, data): """dissect the IPv6 package compressed into this IPHC packet. The packet payload needs to be decompressed and depending on the arguments, several conversi...
# uncompress payload packet = IPv6() packet.version = IPHC_DEFAULT_VERSION packet.tc, packet.fl = self._getTrafficClassAndFlowLabel() if not self.nh: packet.nh = self._nhField # HLIM: Hop Limit if self.hlim == 0: packet.hlim = self._hopLi...
<SYSTEM_TASK:> Depending on the payload content, the frame type we should interpretate <END_TASK> <USER_TASK:> Description: def dispatch_hook(cls, _pkt=b"", *args, **kargs): """Depending on the payload content, the frame type we should interpretate"""
# noqa: E501 if _pkt and len(_pkt) >= 1: if orb(_pkt[0]) == 0x41: return LoWPANUncompressedIPv6 if orb(_pkt[0]) == 0x42: return LoWPAN_HC1 if orb(_pkt[0]) >> 3 == 0x18: return LoWPANFragmentationFirst elif orb(_pkt...