INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
This function is called during sendrecv() routine to select the available sockets.
def _select_nonblock(sockets, remain=None): """This function is called during sendrecv() routine to select the available sockets. """ # pcap sockets aren't selectable, so we return all of them # and ask the selecting functions to use nonblock_recv instead of recv def _sleep_nonblock_recv(self): ...
Get old-format BPF Pointer. Deprecated
def _legacy_bpf_pointer(tcpdump_lines): """Get old-format BPF Pointer. Deprecated""" X86_64 = os.uname()[4] in ['x86_64', 'aarch64'] size = int(tcpdump_lines[0]) bpf = b"" for l in tcpdump_lines[1:]: if six.PY2: int_type = long # noqa: F821 else: int_type = i...
Create a BPF Pointer for TCPDump filter
def get_bpf_pointer(tcpdump_lines): """Create a BPF Pointer for TCPDump filter""" if conf.use_pypy: return _legacy_bpf_pointer(tcpdump_lines) # Allocate BPF instructions size = int(tcpdump_lines[0]) bpf_insn_a = bpf_insn * size bip = bpf_insn_a() # Fill the BPF instruction structur...
Asks Tcpdump to parse the filter, then build the matching BPF bytecode using get_bpf_pointer.
def compile_filter(bpf_filter, iface=None): """Asks Tcpdump to parse the filter, then build the matching BPF bytecode using get_bpf_pointer. """ if not TCPDUMP: raise Scapy_Exception("tcpdump is not available. Cannot use filter !") try: process = subprocess.Popen([ conf.p...
Return the length of the `id` field, according to its real encoded type
def _ldp_id_adjustlen(pkt, x): """Return the length of the `id` field, according to its real encoded type""" f, v = pkt.getfield_and_val('id') return len(_LLDPidField.i2m(f, pkt, v)) + 1
calculate size of lower dot1q layers (if present) :param layer: the layer to start at :return: size of vlan headers, layer below lowest vlan header
def _dot1q_headers_size(layer): """ calculate size of lower dot1q layers (if present) :param layer: the layer to start at :return: size of vlan headers, layer below lowest vlan header """ vlan_headers_size = 0 under_layer = layer while under_layer and is...
check if the structure of the frame is conform to the basic frame structure defined by the standard :param structure_description: string-list reflecting LLDP-msg structure
def _frame_structure_check(structure_description): """ check if the structure of the frame is conform to the basic frame structure defined by the standard :param structure_description: string-list reflecting LLDP-msg structure """ standard_frame_structure = [LLDPDUChassi...
check if multiplicity of present TLVs conforms to the standard :param tlv_type_count: dict containing counte-per-TLV
def _tlv_multiplicities_check(tlv_type_count): """ check if multiplicity of present TLVs conforms to the standard :param tlv_type_count: dict containing counte-per-TLV """ # * : 0..n, 1 : one and only one. standard_multiplicities = { LLDPDUEndOfLLDPDU.__name_...
run layer specific checks
def _check(self): """ run layer specific checks """ if conf.contribs['LLDP'].strict_mode() and self._length != 2: raise LLDPInvalidLengthField('length must be 2 - got ' '{}'.format(self._length))
run layer specific checks
def _check(self): """ run layer specific checks """ if conf.contribs['LLDP'].strict_mode(): management_address_len = len(self.management_address) if management_address_len == 0 or management_address_len > 31: raise LLDPInvalidLengthField( ...
Return all Windows ICMP stats from iphlpapi
def GetIcmpStatistics(): """Return all Windows ICMP stats from iphlpapi""" statistics = MIB_ICMP() _GetIcmpStatistics(byref(statistics)) results = _struct_to_dict(statistics) del(statistics) return results
Return all Windows Adapters addresses from iphlpapi
def GetAdaptersAddresses(AF=AF_UNSPEC): """Return all Windows Adapters addresses from iphlpapi""" # We get the size first size = ULONG() flags = GAA_FLAG_INCLUDE_PREFIX res = _GetAdaptersAddresses(AF, flags, None, None, byref(size)) ...
Return all Windows routes (IPv4 only) from iphlpapi
def GetIpForwardTable(): """Return all Windows routes (IPv4 only) from iphlpapi""" # We get the size first size = ULONG() res = _GetIpForwardTable(None, byref(size), False) if res != 0x7a: # ERROR_INSUFFICIENT_BUFFER -> populate size raise RuntimeError("Error getting structure length (%d)" ...
Return all Windows routes (IPv4/IPv6) from iphlpapi
def GetIpForwardTable2(AF=AF_UNSPEC): """Return all Windows routes (IPv4/IPv6) from iphlpapi""" if WINDOWS_XP: raise OSError("Not available on Windows XP !") table = PMIB_IPFORWARD_TABLE2() res = _GetIpForwardTable2(AF, byref(table)) if res != NO_ERROR: raise RuntimeError("Error retr...
Encrypt the data. Also, update the cipher iv. This is needed for SSLv3 and TLS 1.0. For TLS 1.1/1.2, it is overwritten in TLS.post_build().
def encrypt(self, data): """ Encrypt the data. Also, update the cipher iv. This is needed for SSLv3 and TLS 1.0. For TLS 1.1/1.2, it is overwritten in TLS.post_build(). """ if False in six.itervalues(self.ready): raise CipherError(data) encryptor = self._ciphe...
Decrypt the data. Also, update the cipher iv. This is needed for SSLv3 and TLS 1.0. For TLS 1.1/1.2, it is overwritten in TLS.pre_dissect(). If we lack the key, we raise a CipherError which contains the input.
def decrypt(self, data): """ Decrypt the data. Also, update the cipher iv. This is needed for SSLv3 and TLS 1.0. For TLS 1.1/1.2, it is overwritten in TLS.pre_dissect(). If we lack the key, we raise a CipherError which contains the input. """ if False in six.itervalues(se...
Pack RADIUS data prior computing the authentication MAC
def prepare_packed_data(radius_packet, packed_req_authenticator): """ Pack RADIUS data prior computing the authentication MAC """ packed_hdr = struct.pack("!B", radius_packet.code) packed_hdr += struct.pack("!B", radius_packet.id) packed_hdr += struct.pack("!H", radius_packet.len) packed_a...
Registers the RADIUS attributes defined in this module.
def register_variant(cls): """ Registers the RADIUS attributes defined in this module. """ if hasattr(cls, "val"): cls.registered_attributes[cls.val] = cls else: cls.registered_attributes[cls.type.default] = cls
Returns the right RadiusAttribute class for the given data.
def dispatch_hook(cls, _pkt=None, *args, **kargs): """ Returns the right RadiusAttribute class for the given data. """ if _pkt: attr_type = orb(_pkt[0]) return cls.registered_attributes.get(attr_type, cls) return cls
Computes the "Message-Authenticator" of a given RADIUS packet.
def compute_message_authenticator(radius_packet, packed_req_authenticator, shared_secret): """ Computes the "Message-Authenticator" of a given RADIUS packet. """ data = prepare_packed_data(radius_packet, packed_req_authenticator) radius_hmac...
Computes the authenticator field (RFC 2865 - Section 3)
def compute_authenticator(self, packed_request_auth, shared_secret): """ Computes the authenticator field (RFC 2865 - Section 3) """ data = prepare_packed_data(self, packed_request_auth) radius_mac = hashlib.md5(data + shared_secret) return radius_mac.digest()
We need this hack, else 'self' would be replaced by __iter__.next().
def do_build(self): """ We need this hack, else 'self' would be replaced by __iter__.next(). """ tmp = self.explicit self.explicit = True b = super(KeyShareEntry, self).do_build() self.explicit = tmp return b
This is called by post_build() for key creation.
def create_privkey(self): """ This is called by post_build() for key creation. """ if self.group in _tls_named_ffdh_groups: params = _ffdh_groups[_tls_named_ffdh_groups[self.group]][0] privkey = params.generate_private_key() self.privkey = privkey ...
We attempt to guess the name of interfaces that are truncated from the output of ifconfig -l. If there is only one possible candidate matching the interface name then we return it. If there are none or more, then we return None.
def _guess_iface_name(netif): """ We attempt to guess the name of interfaces that are truncated from the output of ifconfig -l. If there is only one possible candidate matching the interface name then we return it. If there are none or more, then we return None. """ with os.popen('%s -l'...
Returns a list of IPv6 addresses configured on the interface ifname.
def _in6_getifaddr(ifname): """ Returns a list of IPv6 addresses configured on the interface ifname. """ # Get the output of ifconfig try: f = os.popen("%s %s" % (conf.prog.ifconfig, ifname)) except OSError: log_interactive.warning("Failed to execute ifconfig.") return [...
Returns a list of 3-tuples of the form (addr, scope, iface) where 'addr' is the address of scope 'scope' associated to the interface 'iface'. This is the list of all addresses of all interfaces available on the system.
def in6_getifaddr(): """ Returns a list of 3-tuples of the form (addr, scope, iface) where 'addr' is the address of scope 'scope' associated to the interface 'iface'. This is the list of all addresses of all interfaces available on the system. """ # List all network interfaces if O...
Return a list of IPv6 routes than can be used by Scapy.
def read_routes6(): """Return a list of IPv6 routes than can be used by Scapy.""" # Call netstat to retrieve IPv6 routes fd_netstat = os.popen("netstat -rn -f inet6") # List interfaces IPv6 addresses lifaddr = in6_getifaddr() if not lifaddr: return [] # Routes header information ...
Read a config file: execute a python file while loading scapy, that may contain # noqa: E501 some pre-configured values. If _globals or _locals are specified, they will be updated with the loaded vars. # noqa: E501 This allows an external program to use the function. Otherwise, vars are only available #...
def _read_config_file(cf, _globals=globals(), _locals=locals(), interactive=True): # noqa: E501 """Read a config file: execute a python file while loading scapy, that may contain # noqa: E501 some pre-configured values. If _globals or _locals are specified, they will be updated with the loaded vars. # n...
Loads a Python module to make variables, objects and functions available globally. The idea is to load the module using importlib, then copy the symbols to the global symbol table.
def _load(module, globals_dict=None, symb_list=None): """Loads a Python module to make variables, objects and functions available globally. The idea is to load the module using importlib, then copy the symbols to the global symbol table. """ if globals_dict is None: globals_dict = six.moves.bu...
Loads a Scapy module to make variables, objects and functions available globally.
def load_module(name, globals_dict=None, symb_list=None): """Loads a Scapy module to make variables, objects and functions available globally. """ _load("scapy.modules." + name, globals_dict=globals_dict, symb_list=symb_list)
Loads a Scapy layer module to make variables, objects and functions available globally.
def load_layer(name, globals_dict=None, symb_list=None): """Loads a Scapy layer module to make variables, objects and functions available globally. """ _load("scapy.layers." + LAYER_ALIASES.get(name, name), globals_dict=globals_dict, symb_list=symb_list)
Loads a Scapy contrib module to make variables, objects and functions available globally. If no contrib module can be found with the given name, try to find a layer module, since a contrib module may become a layer module.
def load_contrib(name, globals_dict=None, symb_list=None): """Loads a Scapy contrib module to make variables, objects and functions available globally. If no contrib module can be found with the given name, try to find a layer module, since a contrib module may become a layer module. """ try: ...
Show the list of all existing contribs. Params: - name: filter to search the contribs - ret: whether the function should return a dict instead of printing it
def list_contrib(name=None, ret=False, _debug=False): """Show the list of all existing contribs. Params: - name: filter to search the contribs - ret: whether the function should return a dict instead of printing it """ # _debug: checks that all contrib modules have correctly defined: # # s...
Save current Scapy session to the file specified in the fname arg. params: - fname: file to save the scapy session in - session: scapy session to use. If None, the console one will be used - pickleProto: pickle proto version (default: -1 = latest)
def save_session(fname=None, session=None, pickleProto=-1): """Save current Scapy session to the file specified in the fname arg. params: - fname: file to save the scapy session in - session: scapy session to use. If None, the console one will be used - pickleProto: pickle proto version (default...
Load current Scapy session from the file specified in the fname arg. This will erase any existing session. params: - fname: file to load the scapy session from
def load_session(fname=None): """Load current Scapy session from the file specified in the fname arg. This will erase any existing session. params: - fname: file to load the scapy session from""" if fname is None: fname = conf.session try: s = six.moves.cPickle.load(gzip.open(f...
Update current Scapy session from the file specified in the fname arg. params: - fname: file to load the scapy session from
def update_session(fname=None): """Update current Scapy session from the file specified in the fname arg. params: - fname: file to load the scapy session from""" if fname is None: fname = conf.session try: s = six.moves.cPickle.load(gzip.open(fname, "rb")) except IOError: ...
This function processes a quote and returns a string that is ready to be used in the fancy prompt.
def _prepare_quote(quote, author, max_len=78): """This function processes a quote and returns a string that is ready to be used in the fancy prompt. """ quote = quote.split(' ') max_len -= 6 lines = [] cur_line = [] def _len(line): return sum(len(elt) for elt in line) + len(line) -...
Create an interactive session and execute the commands passed as "cmds" and return all output params: - cmds: a list of commands to run returns: (output, returned) The output contains both sys.stdout and sys.stderr logs
def autorun_get_interactive_session(cmds, **kargs): """Create an interactive session and execute the commands passed as "cmds" and return all output params: - cmds: a list of commands to run returns: (output, returned) The output contains both sys.stdout and sys.stderr logs""" sstdout, s...
check if the field addressed by given index relative to this field shares type of this field so we can catch a mix of LEBitField and BitField/other types
def _check_field_type(self, pkt, index): """ check if the field addressed by given index relative to this field shares type of this field so we can catch a mix of LEBitField and BitField/other types """ my_idx = pkt.fields_desc.index(self) try: next_fi...
extract data from raw str collect all instances belonging to the bit field set. if we reach a field that ends at a octet boundary, dissect the whole bit field at once # noqa: E501 :param pkt: packet instance the field belongs to :param s: raw string representing the frame -or- tuple c...
def getfield(self, pkt, s): """ extract data from raw str collect all instances belonging to the bit field set. if we reach a field that ends at a octet boundary, dissect the whole bit field at once # noqa: E501 :param pkt: packet instance the field belongs to :param ...
need to set the length of the whole PDU manually to avoid any bit fiddling use a dummy class to build the layer content also add padding if frame is < 64 bytes Note: padding only handles Ether/n*Dot1Q/EtherCat (no special mumbo jumbo) :param pkt: raw string containing th...
def post_build(self, pkt, pay): """ need to set the length of the whole PDU manually to avoid any bit fiddling use a dummy class to build the layer content also add padding if frame is < 64 bytes Note: padding only handles Ether/n*Dot1Q/EtherCat (no special mumbo ...
This function implement a limited version of source address selection algorithm defined in section 5 of RFC 3484. The format is very different from that described in the document because it operates on a set of candidate source address for some specific route.
def get_source_addr_from_candidate_set(dst, candidate_set): """ This function implement a limited version of source address selection algorithm defined in section 5 of RFC 3484. The format is very different from that described in the document because it operates on a set of candidate source address ...
Compute the interface ID in modified EUI-64 format associated to the Ethernet address provided as input. value taken by U/L bit in the interface identifier is basically the reversed value of that in given MAC address it can be forced to a specific value by using optional 'ulbit' parameter.
def in6_mactoifaceid(mac, ulbit=None): """ Compute the interface ID in modified EUI-64 format associated to the Ethernet address provided as input. value taken by U/L bit in the interface identifier is basically the reversed value of that in given MAC address it can be forced to a specific value...
Extract the mac address from provided iface ID. Iface ID is provided in printable format ("XXXX:XXFF:FEXX:XXXX", eventually compressed). None is returned on error.
def in6_ifaceidtomac(ifaceid): """ Extract the mac address from provided iface ID. Iface ID is provided in printable format ("XXXX:XXFF:FEXX:XXXX", eventually compressed). None is returned on error. """ try: # Set ifaceid to a binary form ifaceid = inet_pton(socket.AF_INET6, "::"...
Extract the mac address from provided address. None is returned on error.
def in6_addrtomac(addr): """ Extract the mac address from provided address. None is returned on error. """ mask = inet_pton(socket.AF_INET6, "::ffff:ffff:ffff:ffff") x = in6_and(mask, inet_pton(socket.AF_INET6, addr)) ifaceid = inet_ntop(socket.AF_INET6, x)[2:] return in6_ifaceidtomac(if...
Extract the MAC address from a modified EUI-64 constructed IPv6 address provided and use the IANA oui.txt file to get the vendor. The database used for the conversion is the one loaded by Scapy from a Wireshark installation if discovered in a well-known location. None is returned on error, "UNKNOWN" if ...
def in6_addrtovendor(addr): """ Extract the MAC address from a modified EUI-64 constructed IPv6 address provided and use the IANA oui.txt file to get the vendor. The database used for the conversion is the one loaded by Scapy from a Wireshark installation if discovered in a well-known location. ...
Generate a Link-Scoped Multicast Address as described in RFC 4489. Returned value is in printable notation. 'addr' parameter specifies the link-local address to use for generating Link-scoped multicast address IID. By default, the function returns a ::/96 prefix (aka last 32 bits of returned addre...
def in6_getLinkScopedMcastAddr(addr, grpid=None, scope=2): """ Generate a Link-Scoped Multicast Address as described in RFC 4489. Returned value is in printable notation. 'addr' parameter specifies the link-local address to use for generating Link-scoped multicast address IID. By default, the ...
Returns a pseudo-randomly generated Local Unique prefix. Function follows recommendation of Section 3.2.2 of RFC 4193 for prefix generation.
def in6_getLocalUniquePrefix(): """ Returns a pseudo-randomly generated Local Unique prefix. Function follows recommendation of Section 3.2.2 of RFC 4193 for prefix generation. """ # Extracted from RFC 1305 (NTP) : # NTP timestamps are represented as a 64-bit unsigned fixed-point number, ...
Implements the interface ID generation algorithm described in RFC 3041. The function takes the Modified EUI-64 interface identifier generated as described in RFC 4291 and an optional previous history value (the first element of the output of this function). If no previous interface identifier is provide...
def in6_getRandomizedIfaceId(ifaceid, previous=None): """ Implements the interface ID generation algorithm described in RFC 3041. The function takes the Modified EUI-64 interface identifier generated as described in RFC 4291 and an optional previous history value (the first element of the output of ...
Converts an IPv6 address in printable representation to RFC 1924 Compact Representation ;-) Returns None on error.
def in6_ptoc(addr): """ Converts an IPv6 address in printable representation to RFC 1924 Compact Representation ;-) Returns None on error. """ try: d = struct.unpack("!IIII", inet_pton(socket.AF_INET6, addr)) except Exception: return None res = 0 m = [2**96, 2**64, 2*...
Return True if provided address is a Teredo, meaning it is under the /32 conf.teredoPrefix prefix value (by default, 2001::). Otherwise, False is returned. Address must be passed in printable format.
def in6_isaddrTeredo(x): """ Return True if provided address is a Teredo, meaning it is under the /32 conf.teredoPrefix prefix value (by default, 2001::). Otherwise, False is returned. Address must be passed in printable format. """ our = inet_pton(socket.AF_INET6, x)[0:4] teredoPrefix =...
Extract information from a Teredo address. Return value is a 4-tuple made of IPv4 address of Teredo server, flag value (int), mapped address (non obfuscated) and mapped port (non obfuscated). No specific checks are performed on passed address.
def teredoAddrExtractInfo(x): """ Extract information from a Teredo address. Return value is a 4-tuple made of IPv4 address of Teredo server, flag value (int), mapped address (non obfuscated) and mapped port (non obfuscated). No specific checks are performed on passed address. """ addr = ine...
Return True if provided address has an interface identifier part created in modified EUI-64 format (meaning it matches *::*:*ff:fe*:*). Otherwise, False is returned. Address must be passed in printable format.
def in6_iseui64(x): """ Return True if provided address has an interface identifier part created in modified EUI-64 format (meaning it matches *::*:*ff:fe*:*). Otherwise, False is returned. Address must be passed in printable format. """ eui64 = inet_pton(socket.AF_INET6, '::ff:fe00:0') ...
Return link-local solicited-node multicast address for given address. Passed address must be provided in network format. Returned value is also in network format.
def in6_getnsma(a): """ Return link-local solicited-node multicast address for given address. Passed address must be provided in network format. Returned value is also in network format. """ r = in6_and(a, inet_pton(socket.AF_INET6, '::ff:ffff')) r = in6_or(inet_pton(socket.AF_INET6, 'ff02:...
Return the anycast address associated with all home agents on a given subnet.
def in6_getha(prefix): """ Return the anycast address associated with all home agents on a given subnet. """ r = in6_and(inet_pton(socket.AF_INET6, prefix), in6_cidr2mask(64)) r = in6_or(r, inet_pton(socket.AF_INET6, '::fdff:ffff:ffff:fffe')) return inet_ntop(socket.AF_INET6, r)
Returns True when 'addr' belongs to prefix/plen. False otherwise.
def in6_isincluded(addr, prefix, plen): """ Returns True when 'addr' belongs to prefix/plen. False otherwise. """ temp = inet_pton(socket.AF_INET6, addr) pref = in6_cidr2mask(plen) zero = inet_pton(socket.AF_INET6, prefix) return zero == in6_and(temp, pref)
Return True if provided address is a link-local solicited node multicast address, i.e. belongs to ff02::1:ff00:0/104. False is returned otherwise.
def in6_isllsnmaddr(str): """ Return True if provided address is a link-local solicited node multicast address, i.e. belongs to ff02::1:ff00:0/104. False is returned otherwise. """ temp = in6_and(b"\xff" * 13 + b"\x00" * 3, inet_pton(socket.AF_INET6, str)) temp2 = b'\xff\x02\x00\x00\x00\x00\...
Returns the scope of the address.
def in6_getscope(addr): """ Returns the scope of the address. """ if in6_isgladdr(addr) or in6_isuladdr(addr): scope = IPV6_ADDR_GLOBAL elif in6_islladdr(addr): scope = IPV6_ADDR_LINKLOCAL elif in6_issladdr(addr): scope = IPV6_ADDR_SITELOCAL elif in6_ismaddr(addr): ...
Return common prefix length of IPv6 addresses a and b.
def in6_get_common_plen(a, b): """ Return common prefix length of IPv6 addresses a and b. """ def matching_bits(byte1, byte2): for i in range(8): cur_mask = 0x80 >> i if (byte1 & cur_mask) != (byte2 & cur_mask): return i return 8 tmpA = inet_p...
Return True if 'address' is a valid IPv6 address string, False otherwise.
def in6_isvalid(address): """Return True if 'address' is a valid IPv6 address string, False otherwise.""" try: socket.inet_pton(socket.AF_INET6, address) return True except Exception: return False
Returns the IPv4 address configured on 'ifname', packed with inet_pton.
def get_if_raw_addr(ifname): """Returns the IPv4 address configured on 'ifname', packed with inet_pton.""" # noqa: E501 # Get ifconfig output try: fd = os.popen("%s %s" % (conf.prog.ifconfig, ifname)) except OSError as msg: warning("Failed to execute ifconfig: (%s)", msg) retur...
Returns the packed MAC address configured on 'ifname'.
def get_if_raw_hwaddr(ifname): """Returns the packed MAC address configured on 'ifname'.""" NULL_MAC_ADDRESS = b'\x00' * 6 # Handle the loopback interface separately if ifname == LOOPBACK_NAME: return (ARPHDR_LOOPBACK, NULL_MAC_ADDRESS) # Get ifconfig output try: fd = os.popen...
Returns an opened BPF file object
def get_dev_bpf(): """Returns an opened BPF file object""" # Get the first available BPF handle for bpf in range(256): try: fd = os.open("/dev/bpf%i" % bpf, os.O_RDWR) return (fd, bpf) except OSError: continue raise Scapy_Exception("No /dev/bpf handl...
Attach a BPF filter to the BPF file descriptor
def attach_filter(fd, bpf_filter, iface): """Attach a BPF filter to the BPF file descriptor""" bp = compile_filter(bpf_filter, iface) # Assign the BPF program to the interface ret = LIBC.ioctl(c_int(fd), BIOCSETF, cast(pointer(bp), c_char_p)) if ret < 0: raise Scapy_Exception("Can't attach t...
Returns a list containing all network interfaces.
def get_if_list(): """Returns a list containing all network interfaces.""" # Get ifconfig output try: fd = os.popen("%s -a" % conf.prog.ifconfig) except OSError as msg: raise Scapy_Exception("Failed to execute ifconfig: (%s)" % msg) # Get interfaces interfaces = [line[:line.fin...
Returns an ordered list of interfaces that could be used with BPF. Note: the order mimics pcap_findalldevs() behavior
def get_working_ifaces(): """ Returns an ordered list of interfaces that could be used with BPF. Note: the order mimics pcap_findalldevs() behavior """ # Only root is allowed to perform the following ioctl() call if os.getuid() != 0: return [] # Test all network interfaces inte...
Creates a temporary file. :param keep: If False, automatically delete the file when Scapy exits. :param autoext: Suffix to add to the generated file name. :param fd: If True, this returns a file-like object with the temporary file opened. If False (default), this returns a file path.
def get_temp_file(keep=False, autoext="", fd=False): """Creates a temporary file. :param keep: If False, automatically delete the file when Scapy exits. :param autoext: Suffix to add to the generated file name. :param fd: If True, this returns a file-like object with the temporary file o...
Creates a temporary file, and returns its name. :param keep: If False (default), the directory will be recursively deleted when Scapy exits. :return: A full path to a temporary directory.
def get_temp_dir(keep=False): """Creates a temporary file, and returns its name. :param keep: If False (default), the directory will be recursively deleted when Scapy exits. :return: A full path to a temporary directory. """ dname = tempfile.mkdtemp(prefix="scapy") if not kee...
Restarts scapy
def restart(): """Restarts scapy""" if not conf.interactive or not os.path.isfile(sys.argv[0]): raise OSError("Scapy was not started from console") if WINDOWS: try: res_code = subprocess.call([sys.executable] + sys.argv) except KeyboardInterrupt: res_code = 1 ...
Build a tcpdump like hexadecimal view :param x: a Packet :param dump: define if the result must be printed or returned in a variable :returns: a String only when dump=True
def hexdump(x, dump=False): """Build a tcpdump like hexadecimal view :param x: a Packet :param dump: define if the result must be printed or returned in a variable :returns: a String only when dump=True """ s = "" x = bytes_encode(x) x_len = len(x) i = 0 while i < x_len: ...
Build an equivalent view of hexdump() on a single line Note that setting both onlyasc and onlyhex to 1 results in a empty output :param x: a Packet :param onlyasc: 1 to display only the ascii view :param onlyhex: 1 to display only the hexadecimal view :param dump: print the view if False :retu...
def linehexdump(x, onlyasc=0, onlyhex=0, dump=False): """Build an equivalent view of hexdump() on a single line Note that setting both onlyasc and onlyhex to 1 results in a empty output :param x: a Packet :param onlyasc: 1 to display only the ascii view :param onlyhex: 1 to display only the hexade...
Build a per byte hexadecimal representation Example: >>> chexdump(IP()) 0x45, 0x00, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x40, 0x00, 0x7c, 0xe7, 0x7f, 0x00, 0x00, 0x01, 0x7f, 0x00, 0x00, 0x01 # noqa: E501 :param x: a Packet :param dump: print the view if False :returns: a String only i...
def chexdump(x, dump=False): """Build a per byte hexadecimal representation Example: >>> chexdump(IP()) 0x45, 0x00, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x40, 0x00, 0x7c, 0xe7, 0x7f, 0x00, 0x00, 0x01, 0x7f, 0x00, 0x00, 0x01 # noqa: E501 :param x: a Packet :param dump: print the view if...
Build a fancy tcpdump like hex from bytes.
def hexstr(x, onlyasc=0, onlyhex=0, color=False): """Build a fancy tcpdump like hex from bytes.""" x = bytes_encode(x) _sane_func = sane_color if color else sane s = [] if not onlyasc: s.append(" ".join("%02X" % orb(b) for b in x)) if not onlyhex: s.append(_sane_func(x)) retu...
Show differences between 2 binary strings
def hexdiff(x, y): """Show differences between 2 binary strings""" x = bytes_encode(x)[::-1] y = bytes_encode(y)[::-1] SUBST = 1 INSERT = 1 d = {(-1, -1): (0, (-1, -1))} for j in range(len(y)): d[-1, j] = d[-1, j - 1][0] + INSERT, (-1, j - 1) for i in range(len(x)): d[i, ...
Calculates the Fletcher-16 checkbytes returned as 2 byte binary-string. Including the bytes into the buffer (at the position marked by offset) the # noqa: E501 global Fletcher-16 checksum of the buffer will be 0. Thus it is easy to verify # noqa: E501 the integrity of the buffer on the receiver ...
def fletcher16_checkbytes(binbuf, offset): """Calculates the Fletcher-16 checkbytes returned as 2 byte binary-string. Including the bytes into the buffer (at the position marked by offset) the # noqa: E501 global Fletcher-16 checksum of the buffer will be 0. Thus it is easy to verify # noqa: E501 ...
Returns a random string of length l (l >= 0)
def randstring(l): """ Returns a random string of length l (l >= 0) """ return b"".join(struct.pack('B', random.randint(0, 255)) for _ in range(l))
Returns the binary XOR of the 2 provided strings s1 and s2. s1 and s2 must be of same length.
def strxor(s1, s2): """ Returns the binary XOR of the 2 provided strings s1 and s2. s1 and s2 must be of same length. """ return b"".join(map(lambda x, y: chb(orb(x) ^ orb(y)), s1, s2))
do_graph(graph, prog=conf.prog.dot, format="svg", target="| conf.prog.display", options=None, [string=1]): string: if not None, simply return the graph string graph: GraphViz graph description format: output type (svg, ps, gif, jpg, etc.), passed to dot's "-T" option target: filename or redirec...
def do_graph(graph, prog=None, format=None, target=None, type=None, string=None, options=None): # noqa: E501 """do_graph(graph, prog=conf.prog.dot, format="svg", target="| conf.prog.display", options=None, [string=1]): string: if not None, simply return the graph string graph: GraphViz graph descr...
Pickle a Python object
def save_object(fname, obj): """Pickle a Python object""" fd = gzip.open(fname, "wb") six.moves.cPickle.dump(obj, fd) fd.close()
Corrupt a given percentage or number of bytes from a string
def corrupt_bytes(s, p=0.01, n=None): """Corrupt a given percentage or number of bytes from a string""" s = array.array("B", bytes_encode(s)) s_len = len(s) if n is None: n = max(1, int(s_len * p)) for i in random.sample(range(s_len), n): s[i] = (s[i] + random.randint(1, 255)) % 256 ...
Write a list of packets to a pcap file filename: the name of the file to write packets to, or an open, writable file-like object. The file descriptor will be closed at the end of the call, so do not use an object you do not want to close (e.g., running wrpcap(sys.stdout, []) in ...
def wrpcap(filename, pkt, *args, **kargs): """Write a list of packets to a pcap file filename: the name of the file to write packets to, or an open, writable file-like object. The file descriptor will be closed at the end of the call, so do not use an object you do not want to close (...
Read a pcap or pcapng file and return a packet list count: read only <count> packets
def rdpcap(filename, count=-1): """Read a pcap or pcapng file and return a packet list count: read only <count> packets """ with PcapReader(filename) as fdesc: return fdesc.read_all(count=count)
Imports a tcpdump like hexadecimal view e.g: exported via hexdump() or tcpdump or wireshark's "export as hex"
def import_hexcap(): """Imports a tcpdump like hexadecimal view e.g: exported via hexdump() or tcpdump or wireshark's "export as hex" """ re_extract_hexcap = re.compile(r"^((0x)?[0-9a-fA-F]{2,}[ :\t]{,3}|) *(([0-9a-fA-F]{2} {,2}){,16})") # noqa: E501 p = "" try: while True: ...
Runs Wireshark on a list of packets. See :func:`tcpdump` for more parameter description. Note: this defaults to wait=False, to run Wireshark in the background.
def wireshark(pktlist, wait=False, **kwargs): """ Runs Wireshark on a list of packets. See :func:`tcpdump` for more parameter description. Note: this defaults to wait=False, to run Wireshark in the background. """ return tcpdump(pktlist, prog=conf.prog.wireshark, wait=wait, **kwargs)
Run tshark on a list of packets. :param args: If not specified, defaults to ``tshark -V``. See :func:`tcpdump` for more parameters.
def tdecode(pktlist, args=None, **kwargs): """ Run tshark on a list of packets. :param args: If not specified, defaults to ``tshark -V``. See :func:`tcpdump` for more parameters. """ if args is None: args = ["-V"] return tcpdump(pktlist, prog=conf.prog.tshark, args=args, **kwargs)
Run tcpdump or tshark on a list of packets. When using ``tcpdump`` on OSX (``prog == conf.prog.tcpdump``), this uses a temporary file to store the packets. This works around a bug in Apple's version of ``tcpdump``: http://apple.stackexchange.com/questions/152682/ Otherwise, the packets are passed in s...
def tcpdump(pktlist, dump=False, getfd=False, args=None, prog=None, getproc=False, quiet=False, use_tempfile=None, read_stdin_opts=None, linktype=None, wait=True): """Run tcpdump or tshark on a list of packets. When using ``tcpdump`` on OSX (``prog == conf.prog.tcpdump``), this uses a ...
Run hexedit on a list of packets, then return the edited packets.
def hexedit(pktlist): """Run hexedit on a list of packets, then return the edited packets.""" f = get_temp_file() wrpcap(f, pktlist) with ContextManagerSubprocess("hexedit()", conf.prog.hexedit): subprocess.call([conf.prog.hexedit, f]) pktlist = rdpcap(f) os.unlink(f) return pktlist
Get terminal width (number of characters) if in a window. Notice: this will try several methods in order to support as many terminals and OS as possible.
def get_terminal_width(): """Get terminal width (number of characters) if in a window. Notice: this will try several methods in order to support as many terminals and OS as possible. """ # Let's first try using the official API # (Python 3.3+) if not six.PY2: import shutil s...
Pretty list to fit the terminal, and add header
def pretty_list(rtlst, header, sortBy=0, borders=False): """Pretty list to fit the terminal, and add header""" if borders: _space = "|" else: _space = " " # Windows has a fat terminal border _spacelen = len(_space) * (len(header) - 1) + (10 if WINDOWS else 0) _croped = False ...
Core function of the make_table suite, which generates the table
def __make_table(yfmtfunc, fmtfunc, endline, data, fxyz, sortx=None, sorty=None, seplinefunc=None): # noqa: E501 """Core function of the make_table suite, which generates the table""" vx = {} vy = {} vz = {} vxf = {} # Python 2 backward compatibility fxyz = lambda_tuple_converter(fxyz) ...
Whois client for Python
def whois(ip_address): """Whois client for Python""" whois_ip = str(ip_address) try: query = socket.gethostbyname(whois_ip) except Exception: query = whois_ip s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("whois.ripe.net", 43)) s.send(query.encode("utf8") +...
Open (if necessary) filename, and read the magic.
def open(filename): """Open (if necessary) filename, and read the magic.""" if isinstance(filename, six.string_types): try: fdesc = gzip.open(filename, "rb") magic = fdesc.read(4) except IOError: fdesc = open(filename, "rb") ...
return a list of all packets in the pcap file
def read_all(self, count=-1): """return a list of all packets in the pcap file """ res = [] while count != 0: count -= 1 p = self.read_packet() if p is None: break res.append(p) return res
Read blocks until it reaches either EOF or a packet, and returns None or (packet, (linktype, sec, usec, wirelen)), where packet is a string.
def read_packet(self, size=MTU): """Read blocks until it reaches either EOF or a packet, and returns None or (packet, (linktype, sec, usec, wirelen)), where packet is a string. """ while True: try: blocktype, blocklen = struct.unpack(self.endian + "2I...
Interface Description Block
def read_block_idb(self, block, _): """Interface Description Block""" options = block[16:] tsresol = 1000000 while len(options) >= 4: code, length = struct.unpack(self.endian + "HH", options[:4]) # PCAP Next Generation (pcapng) Capture File Format # 4....
Enhanced Packet Block
def read_block_epb(self, block, size): """Enhanced Packet Block""" intid, tshigh, tslow, caplen, wirelen = struct.unpack( self.endian + "5I", block[:20], ) return (block[20:20 + caplen][:size], RawPcapNgReader.PacketMetadata(linktype=self.interface...
Writes a Packet or bytes to a pcap file. :param pkt: Packet(s) to write (one record for each Packet), or raw bytes to write (as one record). :type pkt: iterable[Packet], Packet or bytes
def write(self, pkt): """ Writes a Packet or bytes to a pcap file. :param pkt: Packet(s) to write (one record for each Packet), or raw bytes to write (as one record). :type pkt: iterable[Packet], Packet or bytes """ if isinstance(pkt, bytes): ...
Writes a single packet to the pcap file. :param packet: Packet, or bytes for a single packet :type packet: Packet or bytes :param sec: time the packet was captured, in seconds since epoch. If not supplied, defaults to now. :type sec: int or long :param usec: ...
def _write_packet(self, packet, sec=None, usec=None, caplen=None, wirelen=None): """ Writes a single packet to the pcap file. :param packet: Packet, or bytes for a single packet :type packet: Packet or bytes :param sec: time the packet was captured, in seco...
Play VoIP packets with RAW data that are either sniffed either from an IP, or specified as a list. It will play only the incoming packets ! :param s1: The IP of the src of all VoIP packets. :param lst: (optional) A list of packets to load :type s1: string :type lst: list :Example: ...
def voip_play(s1, lst=None, **kargs): """Play VoIP packets with RAW data that are either sniffed either from an IP, or specified as a list. It will play only the incoming packets ! :param s1: The IP of the src of all VoIP packets. :param lst: (optional) A list of packets to load :type s1: ...
Same than voip_play, but will play both incoming and outcoming packets. The sound will surely suffer distortion. Only supports sniffing. .. seealso:: voip_play to play only incoming packets.
def voip_play2(s1, **kargs): """ Same than voip_play, but will play both incoming and outcoming packets. The sound will surely suffer distortion. Only supports sniffing. .. seealso:: voip_play to play only incoming packets. """ dsp, rd = os.popen2(sox_base % "-c 2") global x1, ...