Beispiel #1
0
    def listener():
        if continue_listening.isSet():
            packets = protocol.PacketMaker(GET_CHATS)
            server.send(next(packets))
            packet = server.recv(PACKET_SIZE)
            msg = b""
            request, request_id, packet_amount, packet_number, flag = buffer_extractor(
                packet[:HEADER_SIZE])
            msg += packet[HEADER_SIZE:]
            if packet_amount - packet_number > 1:
                for _ in range(packet_amount - 1):
                    packet = server.recv(PACKET_SIZE)
                    msg += packet[HEADER_SIZE:]
            msg = decrypt(msg, key).decode("utf-8")
            chat_list = json.loads(msg)
            cur_list = chat_listbox.get(0, "end")
            for chat in chat_list:
                if chat not in cur_list:
                    chat_types[chat] = chat_list[chat]

                    chat_listbox.insert(tkinter.END, chat)

            i = 0
            for chat in cur_list:
                if chat not in chat_list:
                    chat_listbox.delete(i)
                i += 1

            chat_picker_frame.after(1000, listener)
        else:
            if not stop_listening.isSet():
                chat_picker_frame.after(2000, listener)
Beispiel #2
0
    def open_new_private_chat():
        continue_listening.clear()
        time.sleep(0.05)
        swear_protected = is_swear_protected.get()
        packets = protocol.PacketMaker(CREATE_CHAT,
                                       content=int_to_bytes(swear_protected))
        for packet in packets:
            server.send(packet)

        packet = server.recv(PACKET_SIZE)
        msg = b""
        request, request_id, packet_amount, packet_number, flag = buffer_extractor(
            packet[:HEADER_SIZE])
        msg += packet[HEADER_SIZE:]
        if packet_amount - packet_number > 1:
            for _ in range(packet_amount - 1):
                packet = server.recv(PACKET_SIZE)
                msg += packet[HEADER_SIZE:]
        server_response = decrypt(msg, key).decode("utf-8")
        chat_name, chat_id = server_response.split("~~~")
        user_values.group_key = get_random_bytes(32)
        user_values.rsa_group_key = RSA.generate(2048)
        user_values.pin_code = chat_id
        user_values.chat_name = chat_name
        user_values.is_safe_chat = bool(swear_protected)
        user_values.on_chat_raise()
        stop_listening.set()
        chat_frame.tkraise()
Beispiel #3
0
def get_server_response(server):
    packet = server.recv(PACKET_SIZE)
    content = b''
    request, request_id, packet_amount, packet_number, flag = buffer_extractor(
        packet[:HEADER_SIZE])
    content += packet[HEADER_SIZE:]
    if packet_amount > 1:
        for _ in range(packet_amount - 1):
            packet = server.recv(PACKET_SIZE)
            content += packet[HEADER_SIZE:]
    return request, content.strip(b'\x00')
Beispiel #4
0
def does_user_exist(packet):
    request, request_id, packet_amount, packet_number, flag = buffer_extractor(
        packet[:HEADER_SIZE])

    # packet validity
    if packet_number >= packet_amount:
        raise Exception("this packets are invalid")

    if request == USERNAME_DOESNT_EXIST:
        return False
    elif request == CLIENT_KEYS:
        return True
    else:
        raise Exception(
            "this packet is not a valid type, please check the server side for bugs"
        )
Beispiel #5
0
def can_enter_chat(packet):
    request, request_id, packet_amount, packet_number, flag = buffer_extractor(
        packet[:HEADER_SIZE])

    # packet validity
    if packet_number >= packet_amount:
        raise Exception("this packets are invalid")

    if request == SEND_GROUP_KEYS:
        return True
    elif request == CANT_JOIN_CHAT:
        return False
    else:
        raise Exception(
            "this packet is not a valid type, please check the server side for bugs"
        )
Beispiel #6
0
def is_logged_in(packet):
    request, request_id, packet_amount, packet_number, flag = buffer_extractor(
        packet[:HEADER_SIZE])

    # packet validity
    if packet_number >= packet_amount:
        raise Exception("this packets are invalid")

    if request in [
            REG_LOGIN_SUC, REG_LOGIN_FAIL, AUTHENTICATE_EMAIL, USER_LOGGED_IN
    ]:
        return request, request == REG_LOGIN_SUC
    else:
        # packet validity
        raise Exception(
            "this packet isn't REG_LOGIN type, please check the server side for bugs"
        )
Beispiel #7
0
def can_auth_reset(server_response):
    request, request_id, packet_amount, packet_number, flag = buffer_extractor(
        server_response[:HEADER_SIZE])

    # packet validity
    if packet_number >= packet_amount:
        raise Exception("this packets are invalid")

    if request in [REG_LOGIN_FAIL, AUTHENTICATE_EMAIL, USER_LOGGED_IN]:
        if flag != SOMETHING_ELSE:
            # packet validity
            raise Exception(
                "this packet's request doesn't match the flag \n request == REG_LOGIN_SUC\n flag != R_L_SUC"
            )
        return request == AUTHENTICATE_EMAIL, request
    else:
        # packet validity
        raise Exception(
            "this packet isn't REG_LOGIN type, please check the server side for bugs"
        )
Beispiel #8
0
    def open_new_public_chat():
        continue_listening.clear()
        swear_protected = is_swear_protected.get()
        time.sleep(0.5)
        rsa_key = RSA.generate(2048)
        if swear_protected == 0:
            content = rsa_key.public_key().export_key() + b'\x00'
        elif swear_protected == 1:
            content = rsa_key.public_key().export_key() + b'\x01'
        packets = protocol.PacketMaker(CREATE_PUBLIC_CHAT,
                                       content=content,
                                       shared_secret=key)
        for packet in packets:
            server.send(packet)

        packet = server.recv(PACKET_SIZE)
        msg = b""
        request, request_id, packet_amount, packet_number, flag = buffer_extractor(
            packet[:HEADER_SIZE])
        msg += packet[HEADER_SIZE:]
        if packet_amount - packet_number > 1:
            for _ in range(packet_amount - 1):
                packet = server.recv(PACKET_SIZE)
                msg += packet[HEADER_SIZE:]
        user_values.group_key = AES_crypto.rsa_decrypt(msg, rsa_key)
        user_values.chat_name = user_values.username + "'s public chat"

        if swear_protected:
            user_values.chat_name += " (swear protected)"
            user_values.is_safe_chat = True
        else:
            user_values.is_safe_chat = False

        user_values.on_chat_raise()
        stop_listening.set()
        chat_frame.tkraise()
    def msg_listener(*args):
        if user_values.pin_code or user_values.chat_name:
            server.settimeout(0.04)
            try:
                packet = server.recv(PACKET_SIZE)
                server.settimeout(None)
                msg_queue = []
                request, request_id, packet_amount, packet_number, flag = protocol_digest.buffer_extractor(
                    packet[:HEADER_SIZE])
                msg_queue.append(packet)
                server.settimeout(1)
                if packet_amount - packet_number > 1:
                    for _ in range(packet_amount - 1):
                        packet = server.recv(PACKET_SIZE)
                        msg_queue.append(packet)
                server.settimeout(None)

                # need to check packet validity
                if packet_amount - len(msg_queue):
                    print("f**k, something went wrong")
                    # not every packet was sent for some reason
                    s = list(range(packet_amount))
                    for packet in msg_queue:
                        request, request_id, packet_amount, packet_number, flag = buffer_extractor(
                            packet[:HEADER_SIZE])
                        s.remove(packet_number)
                    print(s)
                    content = request_id + b"," + " ".join(s).encode("utf-8")
                    packets = protocol.PacketMaker(RESEND_PACKETS,
                                                   content=content,
                                                   shared_secret=key)
                    for packet in packets:
                        print(packet)
                        server.send(packet)

                    packet = server.recv(PACKET_SIZE)
                    request, request_id, packet_amount, packet_number, flag = buffer_extractor(
                        packet[:HEADER_SIZE])
                    msg_queue.insert(packet_number, packet)
                    if packet_amount > 1:
                        for _ in range(packet_amount - packet_number - 1):
                            packet = self.client.recv(PACKET_SIZE)
                            self.queue_requests.insert(packet_number, packet)

                if request == SEND_MSG:
                    msg = b''
                    for packet in msg_queue:
                        msg += packet[HEADER_SIZE:]
                    msg = decrypt(msg, user_values.group_key)
                    list_box.insert(tkinter.END, msg.decode("utf-8"))
                elif request in [SEND_FILE, SEND_IMG]:
                    print(packet_amount - len(msg_queue))
                    username = b''
                    file_name = b''
                    file_content = b''
                    for packet in msg_queue:
                        request, request_id, packet_amount, packet_number, flag = protocol_digest.buffer_extractor(
                            packet[:HEADER_SIZE])
                        if flag == FILE_NAME_PACKET:
                            file_name += packet[HEADER_SIZE:]
                        elif flag == CONTENT_PACKET:
                            file_content += packet[HEADER_SIZE:]
                        elif flag == USERNAME_PACKET:
                            username += packet[HEADER_SIZE:]
                    user_values.process_thread.add_request(
                        [request, [file_name, file_content]])
                    username = decrypt(username, user_values.group_key)
                    list_box.insert(tkinter.END,
                                    username.decode("utf-8") + " sent a file")
                    file_path = os.getcwd() + "\\files"
                    clickable_links[username.decode("utf-8") +
                                    " sent a file"] = file_path
                elif request == SENDING_COMPLITED:
                    msg = b''
                    for packet in msg_queue:
                        msg += packet[HEADER_SIZE:]
                    this_request_id = decrypt(msg, key)
                    del file_packet_list[this_request_id]
                elif request == RESEND_PACKETS:
                    msg = b''
                    for packet in msg_queue:
                        msg += packet[HEADER_SIZE:]
                    this_request_id, item_list = decrypt(msg, key)
                    item_list = item_list.split(" ")
                    for number in item_list:
                        packet = file_packet_list[this_request_id].index(
                            number)
                        server.send(packet)

                elif request == GET_GROUP_INFO:
                    msg = b''
                    for packet in msg_queue:
                        msg += packet[HEADER_SIZE:]
                    user_values.process_thread.add_request([request, msg])
                else:
                    msg = b''
                    for packet in msg_queue:
                        msg += packet[HEADER_SIZE:]
                    user_values.process_thread.add_request([request, msg])

            except Exception as e:
                if type(e) != socket.timeout:
                    raise e
                else:
                    server.settimeout(None)
            finally:
                chat_frame.after(300, msg_listener)
Beispiel #10
0
    def on_select(event):
        if not continue_listening.isSet():
            return
        continue_listening.clear()

        courser = chat_listbox.curselection()
        if not courser:
            return
        value = chat_listbox.get(courser)
        if value[-11:] == "(safe chat)":
            user_values.is_safe_chat = True
        else:
            user_values.is_safe_chat = False

        if chat_types[value] == "private":
            top = tkinter.Toplevel()

            def join_chat(*args):
                continue_listening.clear()
                pin_error.grid_forget()
                pin_code = pin_code_entry.get()

                if not pin_code:
                    pin_error.grid(row=3, column=0, sticky="N")
                else:
                    rsa_key = RSA.generate(2048)
                    content = {
                        "chat_name": value,
                        "pin_code": pin_code,
                        "rsa_key": rsa_key.export_key("PEM").decode("utf-8")
                    }
                    content = json.dumps(content).encode("utf-8")
                    packets = protocol.PacketMaker(JOIN_CHAT,
                                                   shared_secret=key,
                                                   content=content)
                    for packet in packets:
                        server.send(packet)

                    request, server_response = get_server_response(server)
                    if request == SEND_GROUP_KEYS:
                        group_private_key, group_dh_key = server_response.strip(
                            b'\x00').split(b"end_private_key")
                        user_values.rsa_group_key = AES_crypto.rsa_decrypt(
                            group_private_key, rsa_key)
                        group_private_key = RSA.import_key(
                            user_values.rsa_group_key)
                        group_dh_key = pow(bytes_to_int(group_dh_key),
                                           group_private_key.d,
                                           group_private_key.n)
                        user_values.group_key = int_to_bytes(group_dh_key)

                        top.withdraw()
                        pin_code_entry.delete(0, "end")
                        user_values.pin_code = pin_code
                        user_values.chat_name = value
                        stop_listening.set()
                        chat_frame.tkraise()
                        user_values.on_chat_raise()
                    elif request == CANT_JOIN_CHAT:
                        pin_error.grid(row=3, column=0, sticky="N")

            top.title("password inserter")

            tkinter.Label(top,
                          text=f"want to join {value}?\nenter password",
                          font=15).grid(row=1, column=0, sticky="S")

            pin_code_entry = tkinter.Entry(top, text="enter password", font=15)
            pin_code_entry.grid(row=2, column=0, pady=20, sticky="NEWS")

            pin_error = tkinter.Label(
                top, text="the pin-code you entered is incorrect", fg="red")

            tkinter.Button(top, text="join chat", font=15,
                           command=join_chat).grid(row=4, column=0, sticky="N")
        else:
            stop_listening.set()
            rsa_key = RSA.generate(2048)
            content = dict(chat_name=value,
                           rsa_key=rsa_key.export_key("PEM").decode("utf-8"))
            content = json.dumps(content).encode("utf-8")
            packets = protocol.PacketMaker(JOIN_PASSWORD_LESS_CHAT,
                                           content=content,
                                           shared_secret=key)
            for packet in packets:
                server.send(packet)

            packet = server.recv(PACKET_SIZE)
            request, request_id, packet_amount, packet_number, flag = buffer_extractor(
                packet[:HEADER_SIZE])
            full_msg = packet[HEADER_SIZE:]
            if packet_amount > 1:
                for _ in range(packet_amount - 1):
                    packet = server.recv(PACKET_SIZE)
                    full_msg += packet[HEADER_SIZE:]
            user_values.group_key = AES_crypto.rsa_decrypt(full_msg, rsa_key)
            user_values.chat_name = value
            chat_frame.tkraise()
            user_values.on_chat_raise()
            stop_listening.set()
    def run(self):
        while self.keep_running:
            # receive packets from client
            packet = self.client.recv(PACKET_SIZE)
            if packet == b'':
                self.close_conn()
                return
            request, request_id, packet_amount, packet_number, flag = buffer_extractor(
                packet[:HEADER_SIZE])
            self.queue_requests.append(packet)
            bad_packets_list = []
            if len(packet) != 1024:
                request, request_id, packet_amount, packet_number, flag = buffer_extractor(
                    packet[:HEADER_SIZE])
                bad_packets_list.append(packet_number)
            if packet_amount > 1:
                for _ in range(packet_amount - packet_number - 1):
                    packet = self.client.recv(PACKET_SIZE)
                    if len(packet) != 1024:
                        request, request_id, packet_amount, packet_number, flag = buffer_extractor(
                            packet[:HEADER_SIZE])
                        bad_packets_list.append(packet_number)
                    self.queue_requests.append(packet)

            # need to check packet validity

            if packet_amount - len(self.queue_requests):
                print("f**k, something went wrong")
                # not every packet was sent for some reason
                packets_not_arrived = list(range(packet_amount))
                print(packets_not_arrived)
                for packet in self.queue_requests:
                    request, request_id, packet_amount, packet_number, flag = buffer_extractor(
                        packet[:HEADER_SIZE])
                    packets_not_arrived.remove(packet_number)
                    print(str(packet_number) + " has arrived safely")
                bad_packets_list = merge_int_lists(bad_packets_list,
                                                   packets_not_arrived)

            print(packets_not_arrived)

            if bad_packets_list:
                bad_packets_list = list(
                    map(lambda number: str(number), bad_packets_list))
                content = request_id + b"," + " ".join(
                    bad_packets_list).encode("utf-8")
                packets = PacketMaker(RESEND_PACKETS,
                                      content=content,
                                      shared_secret=self.key)
                for packet in packets:
                    print(packet)
                    self.client.send(packet)

                packet = self.client.recv(PACKET_SIZE)
                if packet == b'':
                    self.close_conn()
                    return
                request, request_id, packet_amount, packet_number, flag = buffer_extractor(
                    packet[:HEADER_SIZE])
                self.queue_requests.insert(packet_number, packet)
                if packet_amount > 1:
                    for _ in range(packet_amount - packet_number - 1):
                        packet = self.client.recv(PACKET_SIZE)
                        self.queue_requests.insert(packet_number, packet)

            # sort by request
            if request == SEND_IMG or request == SEND_FILE or request == SEND_MSG:
                print(packet_amount - len(self.queue_requests))
                if request == SEND_FILE or request == SEND_IMG:
                    print("sending file/img " +
                          str(packet_amount - len(self.queue_requests)))
                    packets = PacketMaker(SENDING_COMPLITED,
                                          content=request_id,
                                          shared_secret=self.key)
                    for packet in packets:
                        self.client.send(packet)
                    # s = b''.join(self.queue_requests)
                self.broadcast_packets()
            elif request == LOGIN:
                self.login()
            elif request == REGISTER:
                self.register()
            elif request == JOIN_CHAT:
                self.join_chat()
            elif request == CREATE_CHAT:
                self.create_chat()
            # elif request == GET_USERS:
            #     self.get_users()
            elif request == GET_GROUP_INFO:
                self.get_group_info()
            elif request == RESET_PASSWORD:
                self.reset_password()
            elif request == LEAVE_CHAT:
                self.leave_chat()
            elif request == SEND_PIN_CODE:
                self.authenticate_email()
            elif request == SEND_GROUP_KEYS:
                self.send_group_keys()
            elif request == GET_CHATS:
                self.get_chats()
            elif request == JOIN_PASSWORD_LESS_CHAT:
                self.join_password_less_chat()
            elif request == CREATE_PUBLIC_CHAT:
                self.create_public_chat()
            elif request == CLOSE_CONN:
                self.close_conn()
                return

            self.queue_requests = []
        self.client.close()