#!/usr/bin/env python3 import random import string import json from base64 import b64encode, b64decode import pyDH from Crypto.Hash import SHA512 from Crypto.Cipher import ChaCha20_Poly1305, PKCS1_OAEP from Crypto.PublicKey.RSA import RsaKey from Crypto.Random import get_random_bytes from netsim import network_interface class NetWrapper: def __init__(self, privateKey: RsaKey, clientAddress: str, username: str, serverPubKey: RsaKey, serverAddr: str = 'A'): # Create network_interface: network_interface(path, addr) path root is shared with network / addr is own address self.network = network_interface('./../../netsim/network/', clientAddress) self.serverAddr = serverAddr self.username = username self.privateKey = privateKey self.serverPubKey = serverPubKey self.cipherkey = "".encode('UTF-8') def randomStringGenerator(self, str_size: int = 128, allowed_chars: str = string.ascii_letters + string.punctuation) -> str: return ''.join(random.choice(allowed_chars) for x in range(str_size)) def identifyServer(self) -> bool: randommsg = self.randomStringGenerator() cipher_rsa = PKCS1_OAEP.new(self.serverPubKey) identMsg = json.dumps( {'type': 'IDY', 'source': self.network.own_addr, 'username': self.username, 'message': b64encode(cipher_rsa.encrypt(randommsg.encode('UTF-8'))).decode('ASCII')}).encode( 'UTF-8') self.network.send_msg(self.serverAddr, identMsg) returnJson = {'source': '', 'type': ''} while not (returnJson['source'] == self.serverAddr and returnJson['type'] == 'IDY'): status, msg = self.network.receive_msg(blocking=True) if not status: raise Exception('Network error during connection.') returnJson = json.loads(msg.decode('UTF-8')) cipher_rsa = PKCS1_OAEP.new(self.privateKey) retmsg = cipher_rsa.decrypt(b64decode(returnJson['message'])).decode('UTF-8') return retmsg == randommsg def createEncryptedChannel(self): dh = pyDH.DiffieHellman() cipher_rsa = PKCS1_OAEP.new(self.serverPubKey) mypubkey = b64encode(cipher_rsa.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.serverAddr, jsonmsg) decodedmsg = {'source': '', 'type': ''} while not (decodedmsg['source'] == self.serverAddr 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.privateKey) serverpubkey = int(cipher_rsa.decrypt(b64decode(decodedmsg['message'])).decode('UTF-8')) cipherkey = dh.gen_shared_key(serverpubkey).encode('UTF-8') hasher = SHA512.new() hasher.update(cipherkey) self.cipherkey = (hasher.hexdigest()[:32]).encode('UTF-8') def authenticate(self, password: str): message = f"LIN {self.username} {password}".encode('UTF-8') cipher = ChaCha20_Poly1305.new(key=self.cipherkey) header = json.dumps({'type': 'AUT', 'source': self.network.own_addr}).encode('UTF-8') cipher.update(header) ciphertext, tag = cipher.encrypt_and_digest(message) nonce = b64encode(cipher.nonce).decode('UTF-8') ct = b64encode(ciphertext).decode('UTF-8') b64tag = b64encode(tag).decode('UTF-8') sendjson = json.dumps( {'header': b64encode(header).decode('UTF-8'), 'nonce': nonce, 'message': ct, 'tag': b64tag}).encode( 'UTF-8') self.network.send_msg(self.serverAddr, sendjson) try: 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_Poly1305.new(key=self.cipherkey, nonce=retnonce) retcipher.update(b64decode(b64['header'])) retheader = json.loads(b64decode(b64['header']).decode('UTF-8')) plaintext = retcipher.decrypt_and_verify(retciphertext, b64decode(b64['tag'])).decode('UTF-8') if plaintext != "OK" or not (retheader['source'] == self.serverAddr and retheader['type'] == 'AUT'): raise Exception('Authentication error') except Exception as e: print(e) def connectToServer(self): identStatus = self.identifyServer() if not identStatus: raise Exception('Server identification faliure') self.createEncryptedChannel() print('Please enter your password:') pw = input() self.authenticate(pw) def sendMessage(self, message: bytes): cipher = ChaCha20_Poly1305.new(key=self.cipherkey) header = json.dumps({'type': 'CMD', 'source': self.network.own_addr}).encode('UTF-8') cipher.update(header) ciphertext, tag = cipher.encrypt_and_digest(message) nonce = b64encode(cipher.nonce).decode('UTF-8') ct = b64encode(ciphertext).decode('UTF-8') sendjson = json.dumps({'header': b64encode(header).decode('UTF-8'), 'nonce': nonce, 'message': ct, 'tag': b64encode(tag).decode('UTF-8')}).encode( 'UTF-8') self.network.send_msg(self.serverAddr, sendjson) def recieveMessage(self) -> bytes: try: 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_Poly1305.new(key=self.cipherkey, nonce=retnonce) retcipher.update(b64decode(b64['header'])) plaintext = retcipher.decrypt_and_verify(retciphertext, b64decode(b64['tag'])) retheader = json.loads(b64decode(b64['header']).decode('UTF-8')) if not (retheader['source'] == self.serverAddr and retheader['type'] == 'CMD'): return "ERROR".encode('UTF-8') return plaintext except Exception: print("Incorrect decryption") return "ERROR".encode('UTF-8')