#!/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, 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.new(key=self.cipherkey, nonce=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.serverAddr, sendjson) b64 = {'source': '', 'type': ''} while not (b64['source'] == self.serverAddr 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(key=self.cipherkey, nonce=retnonce) plaintext = retcipher.decrypt(retciphertext).decode('UTF-8') if plaintext != "OK": 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.new(key=self.cipherkey, nonce=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.serverAddr, sendjson) def recieveMessage(self) -> bytes: b64 = {'source': '', 'type': ''} while not (b64['source'] == self.serverAddr 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(key=self.cipherkey, nonce=retnonce) plaintext = retcipher.decrypt(retciphertext) return plaintext except Exception: print("Incorrect decryption") return "ERROR".encode('UTF-8')