text
stringlengths
81
112k
XXX Something should be done about the session ID here. def tls_session_update(self, msg_str): """ XXX Something should be done about the session ID here. """ super(SSLv2ServerHello, self).tls_session_update(msg_str) s = self.tls_session client_cs = s.sslv2_common_cs ...
Generate a range object from (start, stop[, step]) tuples, or return value. def _get_values(value): """Generate a range object from (start, stop[, step]) tuples, or return value. """ if (isinstance(value, tuple) and (2 <= len(value) <= 3) and all(hasattr(i, "__int__") for i in value)):...
psdump(filename=None, layer_shift=0, rebuild=1) Creates an EPS file describing a packet. If filename is not provided a temporary file is created and gs is called. :param filename: the file's filename def psdump(self, filename=None, **kargs): """ psdump(filename=None, layer_shi...
pdfdump(filename=None, layer_shift=0, rebuild=1) Creates a PDF file describing a packet. If filename is not provided a temporary file is created and xpdf is called. :param filename: the file's filename def pdfdump(self, filename=None, **kargs): """ pdfdump(filename=None, layer...
svgdump(filename=None, layer_shift=0, rebuild=1) Creates an SVG file describing a packet. If filename is not provided a temporary file is created and gs is called. :param filename: the file's filename def svgdump(self, filename=None, **kargs): """ svgdump(filename=None, layer_...
Extract description from README.md, for PyPI's usage def get_long_description(): """Extract description from README.md, for PyPI's usage""" try: fpath = os.path.join(os.path.dirname(__file__), "README.md") with io.open(fpath, encoding="utf-8") as f: readme = f.read() des...
Check for odd packet length and pad according to Cisco spec. This padding is only used for checksum computation. The original packet should not be altered. def _check_len(self, pkt): """Check for odd packet length and pad according to Cisco spec. This padding is only used for checksum ...
Legacy method for PKCS1 v1.5 encoding with MD5-SHA1 hash. def _legacy_pkcs1_v1_5_encode_md5_sha1(M, emLen): """ Legacy method for PKCS1 v1.5 encoding with MD5-SHA1 hash. """ M = bytes_encode(M) md5_hash = hashes.Hash(_get_hash("md5"), backend=default_backend()) md5_hash.update(M) sha1_hash ...
Send a DHCP discover request and return the answer def dhcp_request(iface=None, **kargs): """Send a DHCP discover request and return the answer""" if conf.checkIPaddr != 0: warning("conf.checkIPaddr is not 0, I may not be able to match the answer") # noqa: E501 if iface is None: iface = co...
Updates the specified IPython console shell with the conf.color_theme scapy theme. def apply_ipython_style(shell): """Updates the specified IPython console shell with the conf.color_theme scapy theme.""" try: from IPython.terminal.prompts import Prompts, Token except Exception: from...
This get started as a thread, and waits for the data lock to be freed then advertise itself to the SelectableSelector using the callback def _wait_non_ressources(self, callback): """This get started as a thread, and waits for the data lock to be freed then advertise itself to the SelectableSelector using the c...
Entry point of SelectableObject: register the callback def wait_return(self, callback): """Entry point of SelectableObject: register the callback""" if self.check_recv(): return callback(self) _t = threading.Thread(target=self._wait_non_ressources, args=(callback,)) # noqa: E501 ...
DEV: Must be call when the object becomes ready to read. Relesases the lock of _wait_non_ressources def call_release(self, arborted=False): """DEV: Must be call when the object becomes ready to read. Relesases the lock of _wait_non_ressources""" self.was_ended = arborted t...
Releases all locks to kill all threads def _release_all(self): """Releases all locks to kill all threads""" for i in self.inputs: i.call_release(True) self.available_lock.release()
Timeout before releasing every thing, if nothing was returned def _timeout_thread(self, remain): """Timeout before releasing every thing, if nothing was returned""" time.sleep(remain) if not self._ended: self._ended = True self._release_all()
This function is passed to each SelectableObject as a callback The SelectableObjects have to call it once there are ready def _exit_door(self, _input): """This function is passed to each SelectableObject as a callback The SelectableObjects have to call it once there are ready""" self.re...
Entry point of SelectableSelector def process(self): """Entry point of SelectableSelector""" if WINDOWS: select_inputs = [] for i in self.inputs: if not isinstance(i, SelectableObject): warning("Unknown ignored object type: %s", type(i)) ...
Checks that module has a higher version that minver. params: - module: a module to test - minver: a tuple of versions def _version_checker(module, minver): """Checks that module has a higher version that minver. params: - module: a module to test - minver: a tuple of versions """ ...
Check if the cryptography library is present, and if it supports X25519, ChaCha20Poly1305 and such (v2.0 or later). def isCryptographyAdvanced(): """ Check if the cryptography library is present, and if it supports X25519, ChaCha20Poly1305 and such (v2.0 or later). """ try: from cryptog...
Change the current prompt theme def _prompt_changer(attr, val): """Change the current prompt theme""" try: sys.ps1 = conf.color_theme.prompt(conf.prompt) except Exception: pass try: apply_ipython_style(get_ipython()) except NameError: pass
Populate the conf.L2Socket and conf.L3Socket according to the various use_* parameters def _set_conf_sockets(): """Populate the conf.L2Socket and conf.L3Socket according to the various use_* parameters """ if conf.use_bpf and not BSD: Interceptor.set_from_hook(conf, "use_bpf", False) ...
This a decorator to be used for any method relying on the cryptography library. # noqa: E501 Its behaviour depends on the 'crypto_valid' attribute of the global 'conf'. def crypto_validator(func): """ This a decorator to be used for any method relying on the cryptography library. # noqa: E501 Its beh...
Returns a packet list filtered by a truth function. This truth function has to take a packet as the only argument and return a boolean value. def filter(self, func): """Returns a packet list filtered by a truth function. This truth function has to take a packet as the only argument and return a...
Applies a function to each packet to get a value that will be plotted with matplotlib. A list of matplotlib.lines.Line2D is returned. lfilter: a truth function that decides whether a packet must be plotted def plot(self, f, lfilter=None, plot_xy=False, **kargs): """Applies a function to each p...
diffplot(f, delay=1, lfilter=None) Applies a function to couples (l[i],l[i+delay]) A list of matplotlib.lines.Line2D is returned. def diffplot(self, f, delay=1, lfilter=None, **kargs): """diffplot(f, delay=1, lfilter=None) Applies a function to couples (l[i],l[i+delay]) A list...
Uses a function that returns a label and a value for this label, then plots all the values label by label. A list of matplotlib.lines.Line2D is returned. def multiplot(self, f, lfilter=None, plot_xy=False, **kargs): """Uses a function that returns a label and a value for this label, then ...
Same as nsummary(), except that if a packet has a Raw layer, it will be hexdumped # noqa: E501 lfilter: a truth function that decides whether a packet must be displayed def hexraw(self, lfilter=None): """Same as nsummary(), except that if a packet has a Raw layer, it will be hexdumped # noqa: E501 ...
Same as nsummary(), except that packets are also hexdumped lfilter: a truth function that decides whether a packet must be displayed def hexdump(self, lfilter=None): """Same as nsummary(), except that packets are also hexdumped lfilter: a truth function that decides whether a packet must be dis...
Graphes a conversations between sources and destinations and display it (using graphviz and imagemagick) getsrcdst: a function that takes an element of the list and returns the source, the destination and optionally a label. By default, returns the IP source and ...
Experimental clone attempt of http://sourceforge.net/projects/afterglow each datum is reduced as src -> event -> dst and the data are graphed. by default we have IP.src -> IP.dport -> IP.dst def afterglow(self, src=None, event=None, dst=None, **kargs): """Experimental clone attempt of http://so...
sr([multi=1]) -> (SndRcvList, PacketList) Matches packets in the list and return ( (matched couples), (unmatched packets) ) def sr(self, multi=0): """sr([multi=1]) -> (SndRcvList, PacketList) Matches packets in the list and return ( (matched couples), (unmatched packets) )""" # noqa: E501 ...
lst.replace(<field>,[<oldvalue>,]<newvalue>) lst.replace( (fld,[ov],nv),(fld,[ov,]nv),...) if ov is None, all values are replaced ex: lst.replace( IP.src, "192.168.1.1", "10.0.0.1" ) lst.replace( IP.ttl, 64 ) lst.replace( (IP.ttl, 64), (TCP.sport, 666, 777), ) de...
Return True if the tcpdump command can be started def _check_tcpdump(): """ Return True if the tcpdump command can be started """ with open(os.devnull, 'wb') as devnull: try: proc = subprocess.Popen([conf.prog.tcpdump, "--version"], stdout=devnull...
Ease SIOCGIF* ioctl calls def get_if(iff, cmd): """Ease SIOCGIF* ioctl calls""" sck = socket.socket() ifreq = ioctl(sck, cmd, struct.pack("16s16x", iff.encode("utf8"))) sck.close() return ifreq
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 selec...
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: F82...
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()...
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 no...
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 :...
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 ...
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 ...
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 LLDPIn...
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, N...
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 rais...
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 re...
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...
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. Th...
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_...
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.d...
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, c...
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_d...
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 + sha...
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 ...
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_pri...
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 ...
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: l...
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, scop...
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 lifa...
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 #...
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...
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, s...
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), ...
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 con...
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 ...
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, picklePr...
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 sessio...
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 fn...
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 = ...
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 intera...
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 o...
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...
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...
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, ca...
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_mact...
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...
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))...
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 ...
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...
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 ...
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...
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.unpac...
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 t...
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 f...
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 ...
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...
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_INE...
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) re...
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. Fals...
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_SITEL...
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 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 Fal...
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 ms...
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) ...
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...
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 < ...
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) ...
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 t...