#!/usr/bin/env python3 import json from base64 import b64encode, b64decode import pyDH from Crypto.Cipher import PKCS1_OAEP from Crypto.Cipher import ChaCha20 from Crypto.PublicKey.RSA import RsaKey from Crypto.Random import get_random_bytes from netsim import network_interface from authentication import Authetication class NetWrapper: def __init__(self, clientPublicKey: dict, serverPrivateKey: RsaKey, authenticationInstance: Authetication): self.clientPublicKey = clientPublicKey self.currentClientPublicKey = "".encode('UTF-8') self.serverPrivateKey = serverPrivateKey self.cipherkey = "".encode('UTF-8') self.network = network_interface('./../../netsim/network/', 'A') self.clientAddr = "" self.currentUser = "" self.authenticationInstance = authenticationInstance def serverIdentify(self, msg: bytes) -> None: incommingJson = json.loads(msg.decode('UTF-8')) if incommingJson['type'] != "IDY": raise Exception('Wrong message type encountered') self.clientAddr = incommingJson['source'] self.currentUser = incommingJson['username'] self.currentClientPublicKey = self.clientPublicKey[self.currentUser] cipher_rsa = PKCS1_OAEP.new(self.serverPrivateKey) retmsg = cipher_rsa.decrypt(b64decode(incommingJson['message'])).decode('UTF-8') cipher = PKCS1_OAEP.new(self.currentClientPublicKey) identMsg = json.dumps( {'type': 'IDY', 'source': self.network.own_addr, 'message': b64encode(cipher.encrypt(retmsg.encode('UTF-8'))).decode('ASCII')}).encode( 'UTF-8') self.network.send_msg(self.clientAddr, identMsg) def sendMessage(self, message: bytes) -> None: cipher = ChaCha20.new(self.cipherkey, get_random_bytes(12)) ciphertext = cipher.encrypt(message) nonce = b64encode(cipher.nonce).decode('ASCII') ct = b64encode(ciphertext).decode('ASCII') sendjson = json.dumps({'type': 'CMD', 'source': self.network.own_addr, 'nonce': nonce, 'message': ct}).encode( 'UTF-8') self.network.send_msg(self.clientAddr, sendjson) def keyExchange(self) -> None: dh = pyDH.DiffieHellman() cipher = PKCS1_OAEP.new(self.currentClientPublicKey) mypubkey = b64encode(cipher.encrypt(str(dh.gen_public_key()).encode('UTF-8'))).decode('ASCII') jsonmsg = json.dumps({'type': 'DH', 'source': self.network.own_addr, 'message': mypubkey}).encode('UTF-8') self.network.send_msg(self.clientAddr, jsonmsg) decodedmsg = {'source': '', 'type': ''} while not (decodedmsg['source'] == self.clientAddr and decodedmsg['type'] == 'DH'): status, msg = self.network.receive_msg(blocking=True) if not status: raise Exception('Network error during connection.') decodedmsg = json.loads(msg.decode('UTF-8')) cipher_rsa = PKCS1_OAEP.new(self.serverPrivateKey) serverpubkey = int(cipher_rsa.decrypt(b64decode(decodedmsg['message'])).decode('UTF-8')) self.cipherkey = dh.gen_shared_key(serverpubkey).encode('UTF-8') def login(self) -> bool: b64 = {'source': '', 'type': ''} while not (b64['source'] == self.clientAddr and b64['type'] == 'AUT'): status, msg = self.network.receive_msg(blocking=True) if not status: raise Exception('Network error during connection.') b64 = json.loads(msg.decode('UTF-8')) try: retnonce = b64decode(b64['nonce']) retciphertext = b64decode(b64['message']) retcipher = ChaCha20.new(self.cipherkey, nonce=retnonce) plaintext = retcipher.decrypt(retciphertext).decode('UTF-8').split(' ') linsuccess = (not (len(plaintext) != 3 or plaintext[0] != "LIN" or plaintext[ 1] != self.currentUser)) and self.authenticationInstance.login(plaintext[1], plaintext[2]) if linsuccess: message = "OK".encode('UTF-8') else: message = "ERROR".encode('UTF-8') cipher = ChaCha20.new(self.cipherkey, get_random_bytes(12)) ciphertext = cipher.encrypt(message) nonce = b64encode(cipher.nonce).decode('ASCII') ct = b64encode(ciphertext).decode('ASCII') sendjson = json.dumps( {'type': 'AUT', 'source': self.network.own_addr, 'nonce': nonce, 'message': ct}).encode( 'UTF-8') self.network.send_msg(self.clientAddr, sendjson) return linsuccess except Exception: print("Incorrect decryption") def initClientConnection(self, msg: bytes) -> bytes: print('3') try: print('4') self.serverIdentify(msg) print('5') self.keyExchange() print('6') success = self.login() print('7') if success: return "LINOK".encode('UTF-8') else: self.logout() return "LINERROR".encode('UTF-8') except Exception: self.logout() return "LINERROR".encode('UTF-8') def recieveMessage(self) -> bytes: status, msg = self.network.receive_msg(blocking=True) if not status: raise Exception('Network error during connection.') if not self.clientAddr: return self.initClientConnection(msg) else: return self.recieveEncryptedMessage(msg) def logout(self) -> None: self.clientAddr = "" self.cipherkey = "".encode('UTF-8') self.currentClientPublicKey = "".encode('UTF-8') self.currentUser = "" def recieveEncryptedMessage(self, msg: bytes) -> bytes: try: b64 = json.loads(msg.decode('UTF-8')) while not (b64['source'] == self.clientAddr and b64['type'] == 'CMD'): status, msg = self.network.receive_msg(blocking=True) if not status: raise Exception('Network error during connection.') b64 = json.loads(msg.decode('UTF-8')) retnonce = b64decode(b64['nonce']) retciphertext = b64decode(b64['message']) retcipher = ChaCha20.new(self.cipherkey, nonce=retnonce) plaintext = retcipher.decrypt(retciphertext) return plaintext except Exception: print("Incorrect decryption") return "ERROR".encode('UTF-8')