def main(): print('Starting dnspoison.py') #parse args # dnspoison.py [-i interface] [-f hostnames] [-e expression] parser = argparse.ArgumentParser() parser.add_argument('-i', nargs='?', \ choices=[x[1] for x in socket.if_nameindex()], metavar='interfaceName', \ help='specify interface to sniff packets on. Automatically picks if none specified.') #implement an array of options parser.add_argument('-f', metavar='hostnames.txt', \ help='specify ip hostname pairs to hijack. 1 pair per hostname, separated by whitepace') parser.add_argument('-e', metavar='BPF', help='specify BPF expression') parsed = parser.parse_args() print(parsed) if parsed.i == None: interface = socket.if_nameindex()[0][1] else: interface = parsed.i if not parsed.f == None: loadHostnamesFile(parsed.f) sniffLive(interface, parsed.e) return
def get_network_interfaces(skip_loopback=True): interfaces = [ NetworkInterface(iface) for index, iface in socket.if_nameindex() ] if skip_loopback: return [iface for iface in interfaces if not iface.loopback] return interfaces
def main(): #print('Starting sniffer.py') #parse args # sniffer.py [-i interface] [-r tracefile] [-e expression] parser = argparse.ArgumentParser() whereToReadFrom = parser.add_mutually_exclusive_group() whereToReadFrom.add_argument('-i', nargs='?', \ choices=[x[1] for x in socket.if_nameindex()]+['*'], metavar='interfaceName', \ help='specify interface to sniff packets on, default *.') whereToReadFrom.add_argument('-r', nargs=1, metavar='file.cap', help='specify pcap to read from') parser.add_argument('-e', metavar='BPF', help='specify BPF expression') parsed = parser.parse_args() #print(parsed) load_layer('http') load_layer('tls') retval = 0 if not parsed.r == None: retval = parseFromFile(parsed.r, parsed.e) else: sniffLive(parsed.i, parsed.e) return retval
def determine_mac_address(url): """ Determines which MAC address will be used to reached the host at the given url. """ import socket import struct import fcntl from urllib.parse import urlparse def get_mac(ifname): return fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15].encode()) )[16 + 2:].hex()[:12] # 0x8927 is SIOCGIFHWADDR def get_ip(ifname): return socket.inet_ntoa( fcntl.ioctl( s.fileno(), 0x8915, struct.pack( '256s', ifname[:15].encode()))[20:24]) # 0x8915 is SIOCGIFADDR try: parsed_url = urlparse(url) s = socket.create_connection( (parsed_url.hostname, parsed_url.port or (443 if parsed_url.scheme == 'https' else 80)), 10) local_addr, _ = s.getsockname() for _, name in socket.if_nameindex(): try: if get_ip(name) == local_addr: return get_mac(name) except OSError: pass except (TypeError, ValueError, OSError): logging.warning('Could not find MAC address', exc_info=True) return None
def test_get_net_ns_by_fd(self): pid = os.getpid() task = find_task(self.prog, pid) with open(f"/proc/{pid}/ns/net") as file: net = get_net_ns_by_fd(task, file.fileno()) for index, name in socket.if_nameindex(): netdev = netdev_get_by_index(net, index) self.assertEqual(netdev.name.string_().decode(), name) with tempfile.TemporaryFile("rb") as file: self.assertRaisesRegex( ValueError, "not a namespace inode", get_net_ns_by_fd, task, file.fileno(), ) with open(f"/proc/{pid}/ns/mnt") as file: self.assertRaisesRegex( ValueError, "not a network namespace inode", get_net_ns_by_fd, task, file.fileno(), )
def version(request): context = dict() ifaces_list = list() for if_idx, if_name in socket.if_nameindex(): try: ip = get_ip_address(if_name.encode()) except: ip = 'N/A' ifaces_list.append((if_name, ip)) context['ifaces_list'] = ifaces_list with os.popen('/bin/ip address') as pipe: context['ifaces_more_information'] = pipe.read() version_blank = mg.get_version_blank() context['version'] = version_blank context['request'] = request try: context['next'] = request.GET['next'] except Exception as e: context['next'] = '/' return render(request, "06-SCADA设备/00-SCADA程序版本信息.html", context=context)
def test_low_level_address_tuple(self): t = dns.inet.low_level_address_tuple(("1.2.3.4", 53)) self.assertEqual(t, ("1.2.3.4", 53)) t = dns.inet.low_level_address_tuple(("2600::1", 53)) self.assertEqual(t, ("2600::1", 53, 0, 0)) t = dns.inet.low_level_address_tuple(("1.2.3.4", 53), socket.AF_INET) self.assertEqual(t, ("1.2.3.4", 53)) t = dns.inet.low_level_address_tuple(("2600::1", 53), socket.AF_INET6) self.assertEqual(t, ("2600::1", 53, 0, 0)) t = dns.inet.low_level_address_tuple(("fd80::1%2", 53), socket.AF_INET6) self.assertEqual(t, ("fd80::1", 53, 0, 2)) try: # This can fail on windows for python < 3.8, so we tolerate # the failure and only test if we have something we can work # with. info = socket.if_nameindex() except Exception: info = [] if info: # find first thing on list that is not zero (should be first thing! pair = None for p in info: if p[0] != 0: pair = p break if pair: address = "fd80::1%" + pair[1] t = dns.inet.low_level_address_tuple((address, 53), socket.AF_INET6) self.assertEqual(t, ("fd80::1", 53, 0, pair[0])) def bad(): bogus = socket.AF_INET + socket.AF_INET6 + 1 t = dns.inet.low_level_address_tuple(("2600::1", 53), bogus) self.assertRaises(NotImplementedError, bad)
def get_all_ip_addresses(): nic = [] for ix in socket.if_nameindex(): name = ix[1] ip = get_ip_address(name) nic.append((name, ip)) return nic
def load_interfaces(intf_type=INTF.BUILTINS, *, exclude=[]): ''' return list of tuples of specified interface type. [(intf_index, zone, ident)] ''' intf_settings = load_configuration('config')['interfaces'] dnx_interfaces = intf_settings[intf_type.name.lower()] # filtering out loopback during dict comprehension system_interfaces = {v: k for k, v in if_nameindex()[1:]} collected_intfs = [] if (intf_type is INTF.BUILTINS): for intf_name, intf_info in dnx_interfaces.items(): ident = intf_info['ident'] zone = intf_info['zone'] intf_index = system_interfaces.get(ident) if (not intf_index): raise RuntimeError('failed to associate builtin <> system interfaces.') if (intf_name not in exclude): collected_intfs.append((intf_index, zone, ident)) else: raise NotImplementedError('only builtin interfaces are currently supported.') return collected_intfs
def __init__(self): self.SIOCGIFADDR = 0x8915 ifnames = socket.if_nameindex() for pair in ifnames: if pair[1][0] is 'w': self.ifname = pair[1] break
def run(self, terms, variables=None, **kwargs): #self.set_options(var_options=variables, direct=kwargs) for _, name in socket.if_nameindex(): interface = gateway = None try: interface, gateway = get_interfaceinfo(name) if ( interface.is_link_local or interface.is_loopback or interface.is_multicast or interface.is_reserved ): continue break except: continue if interface is None: raise AnsibleLookupError('Failed to find WSL interface details') return [{ 'ip': str(interface), 'prefixlen': interface.network.prefixlen, 'gateway': gateway, }]
def local_ip4_addr_list(): """Return a set of IPv4 address """ nic = set() for ix in socket.if_nameindex(): name = ix[1] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: ip = socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', name[:15].encode("UTF-8")))[20:24]) except OSError as e: if e.errno == 99: # EADDRNOTAVAIL print("Warning!", "Interface: {}".format(name), "IP address not available for interface.", sep='\n') continue else: raise e nic.add(ip) return nic
def local_ip4_addr_list(): """Return a set of IPv4 address You can use `logging.getLogger("dgl-distributed-socket").setLevel(logging.WARNING+1)` to disable the warning here """ assert os.name != 'nt', 'Do not support Windows rpc yet.' nic = set() logger = logging.getLogger("dgl-distributed-socket") for if_nidx in socket.if_nameindex(): name = if_nidx[1] sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: ip_of_ni = fcntl.ioctl(sock.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', name[:15].encode("UTF-8"))) except OSError as e: if e.errno == 99: # EADDRNOTAVAIL logger.warning( "Warning! Interface: %s \n" "IP address not available for interface.", name) continue else: raise e ip_addr = socket.inet_ntoa(ip_of_ni[20:24]) nic.add(ip_addr) return nic
def local_ip4_addr_list(): """Return a set of IPv4 address """ assert os.name != 'nt', 'Do not support Windows rpc yet.' nic = set() for if_nidx in socket.if_nameindex(): name = if_nidx[1] sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: ip_of_ni = fcntl.ioctl(sock.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', name[:15].encode("UTF-8"))) except OSError as e: if e.errno == 99: # EADDRNOTAVAIL print("Warning!", "Interface: {}".format(name), "IP address not available for interface.", sep='\n') continue else: raise e ip_addr = socket.inet_ntoa(ip_of_ni[20:24]) nic.add(ip_addr) return nic
def __init__(self): Gtk.Window.__init__( self, title="CSWIDS - Client-Side Wireless Intrusion Detection System") self.set_border_width(6) #self.set_default_size(200, 400) self.selected_items = [] self.os = sys.platform # Check what OS we are on self.interfaces = socket.if_nameindex( ) # List available network interfaces self.selected_interface = None self.found_access_points = None self.entry = Gtk.Entry() self.entry.set_text("dsv.su.se") self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4) self.button_box = Gtk.Box(spacing=6, homogeneous=True) self.vbox.pack_start(self.button_box, False, False, 6) header = self.header_bar() self.set_titlebar(header) # SSID, Strength, Encryption, MAC, channel, frequency, (list)bitrate, mode # 8 strs for the liststore. The bitrate attribute for networks is a list, so show it in a combobox. self.liststore = Gtk.ListStore(str, int, str, str, str, str, str, str) self.liststore_bitrates = Gtk.ListStore(str) self.textview = Gtk.TextView() self.button_bar() self.ap_list() self.log_area() self.add(self.vbox)
def task2_xdp_start(): device = "lo" print(socket.if_nametoindex("eth1")) mode = BPF.XDP print(socket.if_nameindex()) ret = "XDP_TX" ctxtype = "xdp_md" flags = 0 b = BPF(src_file="xdp.c", cflags=["-w", "-DRETURNCODE=%s" % ret, "-DCTXTYPE=%s" % ctxtype]) fn = b.load_func("xdp_prog1", mode) b.attach_xdp(device, fn, flags) dropcnt = b.get_table("dropcnt") prev = [0] * 256 print("Printing drops per IP protocol-number, hit CTRL+C to stop") while 1: try: for k in dropcnt.keys(): val = dropcnt.sum(k).value i = k.value if val: delta = val - prev[i] prev[i] = val print("{}: {} pkt/s".format(i, delta)) time.sleep(1) except KeyboardInterrupt: print("Removing filter from device") break b.remove_xdp(device, flags)
def send(args): addr = [] for iface in socket.if_nameindex(): iface = iface[1] split = os.popen(f'ip addr show {iface}').read().split("inet ")#[1].split("/")[0] if len(split) < 2: continue split = split[1].split('/') if len(split) < 2: continue ipv4 = split[0] addr.append([iface, ipv4]) message = f"""\ Subject: Templogger connected to the internet To: {args.to} From: {args.from_mail} {addr}""" try: server = smtplib.SMTP_SSL(args.server, args.port) server.login(args.username, args.password) server.sendmail(args.from_mail, args.to, message) print('Sent') except smtplib.SMTPServerDisconnected: print('Failed to connect to the server. Wrong user/password?') except smtplib.SMTPException as e: print('SMTP error occurred: ' + str(e))
def __init__(self): Gtk.Window.__init__(self, title="CSWIDS - Client-Side Wireless Intrusion Detection System") self.set_border_width(6) #self.set_default_size(200, 400) self.selected_items = [] self.os = sys.platform # Check what OS we are on self.interfaces = socket.if_nameindex() # List available network interfaces self.selected_interface = None self.found_access_points = None self.entry = Gtk.Entry() self.entry.set_text("dsv.su.se") self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4) self.button_box = Gtk.Box(spacing=6, homogeneous=True) self.vbox.pack_start(self.button_box, False, False, 6) header = self.header_bar() self.set_titlebar(header) # SSID, Strength, Encryption, MAC, channel, frequency, (list)bitrate, mode # 8 strs for the liststore. The bitrate attribute for networks is a list, so show it in a combobox. self.liststore = Gtk.ListStore(str, int, str, str, str, str, str, str) self.liststore_bitrates = Gtk.ListStore(str) self.textview = Gtk.TextView() self.button_bar() self.ap_list() self.log_area() self.add(self.vbox)
def list_interfaces(skip_loopback=True): interfaces = OrderedDict() for index, iface in socket.if_nameindex(): if skip_loopback and iface == 'lo': continue mac = getHwAddr(iface).replace(':', '-') interfaces[mac] = iface return interfaces
def nic_info(): """ Return a list with tuples containing NIC and IPv4 """ nic = [] for ix in socket.if_nameindex(): name = ix[1] ip = get_ip_address(name) nic.append((name, ip)) return nic
def get_interfaces(): """ return dict full of Interface objects :return: """ interfaces = {} for interface_tuple in socket.if_nameindex(): interface = Interface(interface_tuple) interfaces[interface.name] = interface return interfaces
def getInterfaces(): ''' Returns a list with interface names. The search get the info from socket, then strips away the index from the name. ''' interfaces = [] iface = socket.if_nameindex() # Get the available interfaces from the socket module for i in iface: # And only append the name of the interface interfaces.append(i[1]) return interfaces
def check_system_interfaces(): interfaces_detected = [ intf[1] for intf in socket.if_nameindex() if 'lo' not in intf[1] ] if (len(interfaces_detected) < 3): eprint( f'at least 3 interfaces are required to deploy dnxfirewall. detected: {len(interfaces_detected)}.' ) return interfaces_detected
def list_interfaces(skip_loopback :bool = True) -> Dict[str, str]: interfaces = {} for index, iface in socket.if_nameindex(): if skip_loopback and iface == "lo": continue mac = get_hw_addr(iface).replace(':', '-').lower() interfaces[mac] = iface return interfaces
def get_intf_builtin(zone_name): intf_settings = load_configuration('config')['interfaces'] intf_info = intf_settings['interfaces']['builtins'][zone_name] system_interfaces = {v: k for k, v in if_nameindex()[1:]} ident = intf_info['ident'] intf_index = system_interfaces.get(ident, None) if (not intf_index): raise RuntimeError('failed to determine interface from provided builtin zone.') return {intf_index: (intf_info['zone'], ident)}
def getInterfaces(): ''' Returns a list with interface names. The search get the info from socket, then strips away the index from the name. ''' interfaces = [] iface = socket.if_nameindex( ) # Get the available interfaces from the socket module for i in iface: # And only append the name of the interface interfaces.append(i[1]) return interfaces
def _ip4_addr_list(self): """Return a set of IPv4 address """ nic = set() for ix in socket.if_nameindex(): name = ix[1] ip = self._get_ip_address(name) nic.add(ip) return nic
def main() -> None: running: bool = True localhost_if_name = socket.if_nameindex()[0][1] print(f"Sniffing interface: {localhost_if_name} " "(presumably it is a localhost interface)") capture = pyshark.LiveCapture( interface=localhost_if_name, use_json=True, include_raw=True, ) def sigint_handler( sig: signal.Signals, frame: types.FrameType, ) -> None: print("Stopped sniffing.") running = False # noqa: F841 signal.signal(signal.SIGINT, sigint_handler) for packet in capture.sniff_continuously(): if not running: break print("\n##################### NEW PACKET #######################") tcp_layer = getattr(packet, 'tcp', None) print(f"Packet number: {packet.number}") print(f"Packet captured length: {packet.captured_length}") print(f"Packet layers: {packet.layers}") if tcp_layer is not None: tcp_flags = tcp_layer.flags.hex_value print(f"TCP seq: {tcp_layer.seq}") print(f"TCP syn: {tcp_flags & TCPFlag.PSH}") print(f"TCP ack: {tcp_layer.ack}") print(f"TCP stream: {tcp_layer.stream}") print(f"TCP flags: {tcp_flags:0>9b}") print(f"TCP checksum: {tcp_layer.checksum}") print(f"TCP srcport: {tcp_layer.srcport}") print(f"TCP dstport: {tcp_layer.dstport}") if tcp_flags & TCPFlag.PSH: data_hex_values: List[str] = packet.data.data.split(":") data_characters: List[str] = list( map(lambda hexval: chr(int(hexval, base=16)), data_hex_values)) data_string = "".join(data_characters) print(f"DATA: {data_string}")
def default(self): if not 'Main' in self.settings: self.settings['Main'] = dict() ms = self.settings['Main'] ms['Text editor executable file'] = '' ms['Number of processors'] = 1 ms['Interface'] = 'Does not matter' ms['Temporary directory'] = curdir + sep + 'tmp' ms['Client mode'] = True if osname == 'posix': ms[tuple('Interface')] = list(zip(*if_nameindex()))[1] ms['Interface'] = ['lo'] ms['Number of processors'] = sysconf('SC_NPROCESSORS_ONLN') ms['Client mode'] = False
def local_ip4_addr_list(): """Return a set of IPv4 address """ assert os.name != 'nt', 'Do not support Windows rpc yet.' nic = set() for if_nidx in socket.if_nameindex(): name = if_nidx[1] sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ip_addr = socket.inet_ntoa(fcntl.ioctl( sock.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', name[:15].encode("UTF-8")))[20:24]) nic.add(ip_addr) return nic
def get_nics_from_macs(): """Get nic names from mac address It would look for files /sys/class/net/{nic}/address return nics: dict to get nic from mac. """ nic_output = {} nics = socket.if_nameindex() nics = [list(nic)[1] for nic in nics] for nic in nics: with open('/sys/class/net/{}/address'.format(nic), 'r') as f: nic_output[f.read().rstrip('\r\n')] = nic return nic_output
def main(): interfaces = [] for _, interface_name in (socket.if_nameindex()): interface = {"name": interface_name, "mac": None} sys_interface_dir = pathlib.Path("/sys/class/net/" + interface_name) sys_absolute_interface_dir = sys_interface_dir.resolve() if (not "pci" in str(sys_absolute_interface_dir)): continue with open(str(sys_absolute_interface_dir / "address")) as f: content = f.read() interface["mac"] = content.strip() interfaces.append(interface) interfaces = sorted(interfaces, key=lambda interface: interface["mac"]) for index, interface in enumerate(interfaces): file_path = pathlib.Path("/etc/systemd/network/") interface["name"] = "net" + str(index) with open(str(file_path / ("10-" + interface["name"] + ".link")), "w") as f: f.write("[Match]\n") f.write("MACAddress=%s\n" % (interface["mac"])) f.write("\n") f.write("[Link]\n") f.write("Name=%s\n" % (interface["name"])) f.write("\n") datetime_str = datetime.datetime.now().strftime("%Y-%m-%d--%H-%M-%S") shutil.copyfile("/etc/network/interfaces", "/etc/network/interfaces.bak__%s" % datetime_str) with open("/etc/network/interfaces", "w") as f: f.write("source /etc/network/interfaces.d/*\n") f.write("\n") f.write("auto lo\n") f.write("iface lo inet loopback\n") f.write("\n") for interface in interfaces: f.write("auto %s\n" % (interface["name"])) f.write("iface %s inet manual\n" % (interface["name"])) f.write("\n")
def network_interfaces(): """Return a list of all network interface""" return [tup[1] for tup in socket.if_nameindex()]
help='multicast group (default ff02::2:1001)') parser.add_argument('-i', dest='mcast_ifaces', action='append', metavar='<iface>', help='interface on which the group is joined') parser.add_argument('-d', dest='directory', default='.', metavar='<dir>', help='data provider directory (default: $PWD)') parser.add_argument('-b', dest='batadv_iface', default='bat0', metavar='<iface>', help='batman-adv interface (default: bat0)') args = parser.parse_args() socketserver.ThreadingUDPServer.address_family = socket.AF_INET6 server = socketserver.ThreadingUDPServer( ("", args.port), get_handler(args.directory, {'batadv_dev': args.batadv_iface}) ) if args.mcast_ifaces: group_bin = socket.inet_pton(socket.AF_INET6, args.group) for (inf_id, inf_name) in socket.if_nameindex(): if inf_name in args.mcast_ifaces: mreq = group_bin + struct.pack('@I', inf_id) server.socket.setsockopt( socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq ) server.serve_forever()