def ClientOpStats(sock): toSend = {"msgType": "stats"} # serialization as json toSendAsJson = json.dumps(toSend) try: send_msg(sock, toSendAsJson) received = recv_msg(sock) except: print("Erreur: le serveur semble s'être arreté, le client doit donc se fermer.") exit() receivedAsDict = json.loads(received) if (receivedAsDict["msgType"] == "error"): print("Error:", receivedAsDict["errorType"]) input("Appuyer sur entré pour continuer...") return subjectList = receivedAsDict["subjectList"] dirSize = receivedAsDict["dirSize"] print() print("Nombre total d'email: " + str(len(subjectList)) + ".") print("Taille totale de votre dossier utilisateur sur le serveur: " + str(dirSize / 1000) + "kb.") if len(subjectList) == 0: return print() print("Liste des sujets de vos courriels:") print('\n'.join(subjectList)) print() input("Appuyer sur entré pour continuer...")
def __showMails(self): send_msg(self.s, str(4)) send_msg(self.s, self.username) try: confirmation = recv_msg(self.s) length = int(recv_msg(self.s)) + 1 subjects = recv_msg(self.s) if confirmation == "messageEmpty": print("\nAucun message recu") else: print("\n" + subjects + str(length) + ".Quitter") wantedMessageNo = input("Entrez le numero du message que vous voulez ouvrir: ") if str(length) == wantedMessageNo: send_msg(self.s, "noConsult") self.__showMainMenu() else: send_msg(self.s, "consulting") send_msg(self.s, wantedMessageNo) confirmation = recv_msg(self.s) if confirmation == "messageOk": subject = recv_msg(self.s) subject, extension = subject.split(".") message = recv_msg(self.s) print("\nSujet: " + subject) print(message) elif confirmation == "noMessage": print("Entrez un numero de sujet valide") self.__showMails() else: print("Erreur niveau serveur") except Exception as ex: print(ex)
def ClientOpSendEmail(sock): # 1 - Get recipient, subject and content recipient = input("Entrez l'adresse du destinataire: ") subject = input("Entrez le sujet du courriel: ") content = input("Entrez le contenu du courriel:\n") # 2 - wrap it into json object and send it to the server # creation of the object to send toSend = {"msgType": "sendEmail", "recipient": recipient, "subject": subject, "content": content} # serialization as json toSendAsJson = json.dumps(toSend) # print("Sending: " + toSendAsJson) try: send_msg(sock, toSendAsJson) received = recv_msg(sock) except: print("Erreur: le serveur semble s'être arreté, le client doit donc se fermer.") exit() # print("Received: {0}", received) # 3 - Process the answer from the server # deserialization of the received answer from the server receivedAsDict = json.loads(received) if receivedAsDict["msgType"] == "error": print("Erreur: ", receivedAsDict["errorType"]) return print("Succès: Le message a été avec succès.") return
def __showStats(self): send_msg(self.s, str(5)) send_msg(self.s, self.username) try: nbrMessage = recv_msg(self.s) size = recv_msg(self.s) messageList = recv_msg(self.s) print("\nNombre de message: " + nbrMessage) print("Taille du dossier: " + size) print("Liste de messages:\n" + messageList) except Exception as ex: print("Erreur niveau serveur")
def __createUser(self, s): try: username = recv_msg(s) password = recv_msg(s) hashedPassword = "" if re.search(r"^(?=.*\d)(?=.*[a-zA-Z]).{6,12}$", password): hashedPassword = sha256(password.encode()).hexdigest() else: send_msg(s, "incorrectPassword") filename = "./" + username + "/config.txt" if not os.path.exists(os.path.dirname(filename)): try: os.makedirs(os.path.dirname(filename)) except OSError as ex: if ex.errno != errno.EEXIST: send_msg("race condition") with open(filename, "w") as file: file.write(hashedPassword) send_msg(s, "userCreated") else: send_msg(s, "usernameExists") except Exception as ex: print(ex) self.__listen(s)
def ProcessClientLoop(client): while True: # 1 - get the next msg from the client try: msgReceivedAsJson = recv_msg(client.sock) except: print("User disconnected") return try: # check if the received message is in a valid json format msgReceivedAsDict = json.loads(msgReceivedAsJson) # if msgType does not exist, it will trigger the "except" msgType = msgReceivedAsDict["msgType"] except: msgToSend = { "msgType": "error", "errorType": "Votre message doit être formaté en json et posseder un attribut msgType." } try: print(json.dumps(msgToSend)) send_msg(client.sock, json.dumps(msgToSend)) except: print("Error: client disconnected") return continue msgToSend = {} # 2 - Check if the client is already authentified if client.state is 0: msgToSend = ProcessNotAuthentifiedClient(client, msgReceivedAsDict) elif client.state is 1: msgToSend = ProcessAuthentifiedClient(client, msgReceivedAsDict) # 3 - Send the message resulting from the processing # try sending the message to the client try: print(json.dumps(msgToSend)) send_msg(client.sock, json.dumps(msgToSend)) except: print("Error: client disconnected") return
def __createPassword(self): try: self.password = getpass.getpass("Entrez le mot de passe voulu, il doit contenir entre 6 et 12 carateres dont au moins" "une lettre et un chiffre: ") if re.search(r"^(?=.*\d)(?=.*[a-zA-Z]).{6,12}$", self.password): send_msg(self.s, str(2)) send_msg(self.s, self.username) send_msg(self.s, self.password) else: print("Le mot de passe ne contient pas entre 6-12 caracteres ou au moins une lettre et un chiffre") self.__createPassword() except Exception as ex: print(ex) try: message = recv_msg(self.s) if message == "userCreated": print("Usage cree") self.__showMainMenu() elif message == "usernameExists": print("Usage existe deja veuillez choisir un autre nom d'usage") self.__createUser() elif message == "incorrectPassword": self.__createPassword() else: print("Probleme au niveau du serveur: " + message) self.__showConnexionMenu() except Exception as ex: print(ex)
def __connexionToServer(self): try: self.username = input("\nEntrez votre nom d'usager: ") self.password = getpass.getpass("Entrez votre mot de passe: ") send_msg(self.s, str(1)) send_msg(self.s, self.username) send_msg(self.s, self.password) except Exception as ex: print(ex) try: message = recv_msg(self.s) if message == "passwordOk": self.__showMainMenu() elif message == "passwordWrong": print("Mauvais mot de passe") self.__connexionToServer() elif message == "notExistUsername": print("Le nom d'usage rentrer ne correspond a aucun usage") self.__showConnexionMenu() else: print("Probleme au niveau du serveur: " + message) self.__showConnexionMenu() except Exception as ex: print(ex)
def __sendMail(self): try: dest = self.__destOk() subject = input("Entrez le sujet: ") message = input("Entrez le message: ") send_msg(self.s, str(3)) send_msg(self.s, dest) send_msg(self.s, subject) send_msg(self.s, message) send_msg(self.s, self.username + "@reseauglo.ca") except Exception as ex: print(ex) try: message = recv_msg(self.s) if message == "mailOk": print("Message envoyee!") elif message == "noDest": print("Destinataire non existant!") elif message == "otherDest": print("Message envoyee a un destinataire exterieur!") except Exception as ex: print(ex)
def __connexion(self, s): try: username = recv_msg(s) password = recv_msg(s) hashedPassword = sha256(password.encode()).hexdigest() filename = "./" + username + "/config.txt" if os.path.exists(os.path.dirname(filename)): try: with open(filename, "r") as file: readPassword = file.readline(); if str(hashedPassword) == str(readPassword): send_msg(s, "passwordOk") else: send_msg(s, "passwordWrong") except OSError as ex: if ex.errno != errno.EEXIST: send_msg(s, "race condition") else: send_msg(s, "notExistUsername") except Exception as ex: print(ex) self.__listen(s)
def __sendStats(self, s): username = recv_msg(s) directory = "./" + username size = os.path.getsize(os.path.dirname(directory)) subjectListSent = [] subjectList = [] it = 1 for filename in os.listdir(directory): if filename.endswith(".txt") and filename != "config.txt": subjectList.append(filename) filename, extension = filename.split(".") subjectListSent.append(str(str(it) + "." + filename + "\n")) it += 1 subjectsString = "".join(subjectListSent) send_msg(s, str(len(subjectList))) send_msg(s, str(size)) send_msg(s, subjectsString) self.__listen(s)
def main(): if opts.destination and opts.serveur: write_exception( Exception( "L'application ne peut pas utiliser -d et -s simultanément.")) if opts.port == -1: write_exception(Exception("L'option -p est obligatoire.")) #TODO: retourner un message d'erreur significatif s'il y a une erreur #TODO: chaque message d'erreur (et sa date et heure) doit être écrit dans le fichier Error.log try: if opts.serveur: # mode serveur print( "###############################################################" ) print("Demarrage du serveur ...") serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serversocket.bind(("localhost", opts.port)) serversocket.listen(5) print(f"Ecoute sur le port : {opts.port}") while True: (s, address) = serversocket.accept() print('1e connexion au serveur') print( '----------------------------------------------------------' ) #create a,b p a = trouverNombrePremier() b = entierAleatoire(a) p = entierAleatoire(a) #create public key server_public_key = exponentiationModulaire(b, p, a) print(f"Envoi du modulo : {a}") print(f"Envoi de la base : {b}") print( '----------------------------------------------------------' ) print(f'Cle privee : {p}') print(f'Cle publique a envoyer : {server_public_key}') send_msg(s, str(a)) # send a send_msg(s, str(b)) # send b send_msg(s, str(server_public_key)) # send public key # receive client public key client_public_key = int(recv_msg(s)) print(f'Cle publique recue : {client_public_key}') #calculate shared key shared_key = exponentiationModulaire(client_public_key, p, a) print(f"Cle partagee : {shared_key}") print("au serveur") print( "###############################################################" ) s.close() else: # mode client if not opts.destination: write_exception( Exception( "Le client doit spécifier une destination en utilisant -d." )) print( "###############################################################" ) destination = (opts.destination, opts.port) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(destination) a = int(recv_msg(s)) # receive a print(f"Reception du modulo : {a}") b = int(recv_msg(s)) # receive b print(f'Reception de la base : {b}') print('----------------------------------------------------------') #create q q = entierAleatoire(a) print(f'Cle privee : {q}') #Create public key client_public_key = exponentiationModulaire(b, q, a) print(f'Cle publique a envoyer : {client_public_key}') # receive server public key server_public_key = int(recv_msg(s)) print(f'Cle publique recue : {server_public_key}') #send public key send_msg(s, str(client_public_key)) #calculate shared key shared_key = exponentiationModulaire(server_public_key, q, a) print(f"Cle partagee : {shared_key}") print( "###############################################################" ) s.close() except Exception as e: write_exception(e)
def __showMails(self, s): username = recv_msg(s) directory = "./" + username subjectListSent = [] subjectList = [] it = 1 for filename in os.listdir(directory): if filename.endswith(".txt") and filename != "config.txt": subjectList.append(filename) filename, extension = filename.split(".") subjectListSent.append(str(str(it) + "." + filename + "\n")) it += 1 subjectsString = "".join(subjectListSent) if len(subjectList) == 0: send_msg(s, "messageEmpty") send_msg(s, str(len(subjectList))) send_msg(s, subjectsString) else: send_msg(s, "messageNotEmpty") send_msg(s, str(len(subjectList))) send_msg(s, subjectsString) try: confirmation = recv_msg(s) if confirmation == "consulting": wantedMessageNo = recv_msg(s) wantedMessageNo = int(wantedMessageNo) - 1 subjectWanted = subjectList[wantedMessageNo] filenameWanted = "./" + username + "/" + subjectWanted if os.path.exists(filenameWanted): try: with open(filenameWanted, "r") as file: message = file.readline() send_msg(s, "messageOk") send_msg(s, subjectWanted) send_msg(s, message) except OSError as ex: if ex.errno != errno.EEXIST: send_msg(s, "race condition") else: print("client quit consulting emails") except Exception as iEx: send_msg(s, "noMessage") self.__listen(s)
if value is 1: toSendDict["msgType"] = "connection" elif value is 2: toSendDict["msgType"] = "newAccount" else: print( "Erreur: Veuillez rentrer un chiffre correspondant à un des deux choix proposés." ) continue username = input("Veuillez entrer votre nom d'utilisateur : ") mdp = GetPassword() toSendDict["username"] = username toSendDict["pwd"] = mdp # print("Sending: {0}", json.dumps(toSendDict)) send_msg(s, json.dumps(toSendDict)) received = recv_msg(s) # print("Received: {0}", received) receidAsDict = json.loads(received) if receidAsDict["msgType"] == "error": print("Erreur:", receidAsDict["errorType"]) continue else: MainLoop() break s.close()
opts = parser.parse_args(sys.argv[1:])[0] if opts.serveur: #mode serveur serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serversocket.bind(("localhost", opts.port)) serversocket.listen(5) print("Listening on port " + str(serversocket.getsockname()[1])) i = 0 while True: i += 1 (s, address) = serversocket.accept() print(address) print(s) print(str(i) + "e connexion au serveur") send_msg(s, "Bonjour, mon nom est Serveur. Et vous?\n") nom = recv_msg(s) print("Le nom du client est " + nom) send_msg(s, "Enchante, " + nom) s.close() else: #mode Client destination = (opts.address, opts.port) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(destination) print(recv_msg(s)) send_msg(s, input()) print(recv_msg(s)) s.close()
finish_error('Erreur : L’application ne peut pas utiliser -d et -s simultanément»') serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serversocket.bind(("localhost", opts.port)) serversocket.listen(5) print("Listening on port " + str(serversocket.getsockname()[1])) i = 0 while True: (s, address) = serversocket.accept() i += 1 print(str(i) + " connexion to server") modulo = trouverNombrePremier() base = entierAleatoire(modulo) send_msg(s, str(modulo)) print("Send modulo: " + str(modulo)) send_msg(s, str(base)) print("Send base: " + str(base)) privateKey = entierAleatoire(modulo) publicKey = exponentiationModulaire(base, privateKey, modulo) send_msg(s, str(publicKey)) publicKeyRcv = int(recv_msg(s)) sharedKey = exponentiationModulaire(publicKeyRcv, privateKey, modulo) print("Private key: " + str(privateKey)) print("Public key: " + str(publicKey))
def ClientOpGetEmail(sock): # 1 - Send the getEmail request to the server toSend = {"msgType": "getEmail"} # serialization as json toSendAsJson = json.dumps(toSend) # 2 - Get the server's answer and write it # print("Sending: " + toSendAsJson) try: send_msg(sock, toSendAsJson) received = recv_msg(sock) except: print("Erreur: le serveur semble s'être arreté, le client doit donc se fermer.") exit() # print("Received: {0}", received) receivedAsDict = json.loads(received) if receivedAsDict["msgType"] == "error": print("Erreur:", receivedAsDict["msgType"]) return if 'mailList' not in receivedAsDict: print("Erreur: le serveur ne possède pas de liste d'email") return mailList = receivedAsDict["mailList"] if len(mailList) is 0: print("Info: votre liste de courriels accessibles est actuellement vide") return print("La liste de courriels accessibles a une longueur de: " + str(len(mailList)) + " courriels.") incr = 1 for subject in mailList: print(str(incr) + ".\t" + subject) incr += 1 # 3 - Get the user's choice value = 0 while True: try: value = int(input("Entrez le numéro du courriel que vous souhaitez consulter: ")) except ValueError: value = 0 if value <= 0 or value > len(mailList): print("Erreur: ce que vous avez entré n'est pas un numéro valide") continue break # 4 - Send the server the number user has chosen toSend = {"msgType": "getEmail", "chosenEmailIndex": value - 1} toSendAsJson = json.dumps(toSend) try: send_msg(sock, toSendAsJson) received = recv_msg(sock) except: print("Erreur: le serveur semble s'être arreté, le client doit donc se fermer.") exit() # 5 - Get the answer from the server and write it receivedAsDict = json.loads(received) if receivedAsDict["msgType"] == "error": print("Erreur:", receivedAsDict["msgType"]) return print() print("Destinataire:\t", receivedAsDict["recipient"]) print("Envoyeur:\t", receivedAsDict["sender"]) print("Date:\t", receivedAsDict["date"]) print() print() print("Sujet:", receivedAsDict["subject"]) print() print() print(receivedAsDict["content"]) print() print() input("Appuyer sur entré pour continuer...") return
serversocket.bind(("localhost", opts.port)) serversocket.listen(5) print("Listening on port " + str(serversocket.getsockname()[1])) i = 0 while True: (s, address) = serversocket.accept() i += 1 print(str(i) + "e connexion au serveur") print("----------") m = trouverNombrePremier() n = entierAleatoire(m) print("Envoi du modulo: " + str(m)) print("Envoi de la base: " + str(n)) print("----------") send_msg(s, str(m)) send_msg(s, str(n)) serSecretKey = entierAleatoire(m) serPublicKey = exponentiationModulaire(n, serSecretKey, m) print("Cle privée: " + str(serSecretKey)) print("Cle publique a envoyer: " + str(serPublicKey)) send_msg(s, str(serPublicKey)) pubKeyCli = int(recv_msg(s)) print("Cle publique recu: " + str(pubKeyCli)) servSharedKey = exponentiationModulaire(pubKeyCli, serSecretKey, m) print("Cle partagee: " + str(servSharedKey)) print("----------") s.close() else: #mode client
def __sendMail(self, s): try: dest = recv_msg(s) subject = recv_msg(s) message = recv_msg(s) username = recv_msg(s) if re.search(r".+@reseauglo\.ca", dest): dest1, dest2 = dest.split("@") filename = "./" + dest1 if os.path.exists(filename): try: os.makedirs(os.path.dirname(filename + "/" + subject + ".txt")) except OSError as ex1: if ex1.errno != errno.EEXIST: send_msg(s, "race condition") print(ex1) with open(filename + "/" + subject + ".txt", "w") as file: file.write(message) send_msg(s, "mailOk") else: try: os.makedirs(os.path.dirname("DESTERREUR/" + subject + ".txt")) except OSError as ex1: if ex1.errno != errno.EEXIST: send_msg(s, "race condition") print(ex1) with open("DESTERREUR/" + subject + ".txt", "w") as file: file.write(message) send_msg(s, "noDest") else: msg = MIMEText(message) msg["FROM"] = username msg["TO"] = dest msg["Subject"] = subject try: smtpConnection = smtplib.SMTP(host="smtp.ulaval.ca", timeout=10) smtpConnection.sendmail(username, dest, msg.as_string()) smtpConnection.quit() send_msg(s, "otherDest") except Exception as ex2: send_msg(s, ex2) except Exception as ex: print(ex) self.__listen(s)