def generateKeys(self): ''' Generate new RSA-2048 keys for this client (accurate off) ''' Display.log('Generating new keys...') self.crypto.generate() self.saveKeys() Display.log('Done.\n')
def handle_message(self, relay_msg): """Check validity of payload, then decrypt if we can""" # Validate that the message is appropriate if "message" in relay_msg and "type" not in relay_msg and "message" in relay_msg["message"]: try: to_decrypt = json.dumps(relay_msg["message"]).encode() decrypted = self.crypto.decrypt(to_decrypt) self.parser.handle_message(decrypted) except Exception as msg: Display.warn("Warning: General decryption failure\n\n{0}".format(msg))
def getUid(self): '''Load UID from users.json or create it''' users = json.load(open('config/users.json','r')) try: self.uid = users[self.alias] except Exception as msg: self.uid = self.generateUid(32) Display.warn('Generated New UID: {0}'.format(self.uid)) users[self.alias] = self.uid with open('config/users.json','w') as out: json.dump(users, out)
def __launch__(self, port): ''' Daemonized; Create and bind a socket on the location and port specified at startup ''' try: self.server_type.allow_reuse_address = True httpd = self.server_type(("",port), self.handler_type, self) httpd.serve_forever() # No dice. Kill the process. except socket.error as msg: Display.warn('ERROR: Unable to bind socket: {0}'.format(msg))
def interpret(self, encrypted): ''' Received a message from the TCP Server, so relay it to our message_interpreter ''' try: decrypted = self.crypto.decrypt(encrypted) except Exception as msg: Display.warn('Warning: General decryption failure\n\n{0}'.format(msg)) return #Display.debug(decrypted) if self.parser is not None: self.parser.handleMessage(decrypted)
def do_roll(self, roll_string): ''' Takes a roll string (e.g. '2d4') rolls, then returns the result as an integer. ''' if 'd' not in roll_string: return 'is failing to roll anything coherent' num_dice, suffix = roll_string.split('d') die_type, modifier = self.get_modifier(suffix) rolls = [r.randint(1, int(die_type)) for i in range(int(num_dice))] total = sum(rolls) + int(modifier) Display.log('You rolled a {0} and got a {1}'.format(roll_string, total)) return 'rolls {0} and gets {1}'.format(roll_string, total)
def interpret(self, encrypted): ''' Received a message from the TCP Server, so relay it to our message_interpreter ''' try: decrypted = self.crypto.decrypt(encrypted) except Exception as msg: Display.warn('Warning: General decryption failure\n\n{0}'.format(msg)) return if self.parser is not None: msg_type = decrypted['type'] node = decrypted['sender']['alias'] #Display.subtle('{0} message received from {1}'.format(msg_type, node)) self.parser.handle_message(decrypted)
def send(self, message, target_node, msg_type): '''Actually send an encoded json message to the location and port''' # Gather the target's location and port location, port = target_node.location.split(':') #Display.subtle('Sending a {1} to {0} ({2})'.format(target_node.alias, msg_type, target_node.location)) status = '' try: headers = {'Accept': 'application/json', 'Content-Type': 'application/json', "Connection": "close"} with requests.Session() as s: payload = {"message" : message} url = 'http://{0}:{1}'.format(location, port) r = requests.post(url, json=payload, headers=headers, timeout=1.0) except Exception as msg: # Flag that we encountered an error status = 'Excepted' if status == 'Excepted': status = self.try_relay(target_node.uid, message) if status == 'Failed': Display.error('{1} could not be delivered to {0} ({2})'.format(target_node.alias, msg_type, target_node.location)) if target_node.status != Node.Status.inactive: target_node.status = Node.Status.unknown
def password_loop(self, filename): '''Loops until the correct password is entered''' attempts = 0 while attempts < 3: password = input('Please enter password to unlock ({0} attempts remaining): '.format(3-attempts)) try: with open(filename,'rb') as enc_data: encrypted = pickle.load(enc_data) data = self.keyloader.unlock_with_password(password, encrypted) self.crypto.load(data['privateKey']) Display.log('User settings loaded.') return except: Display.warn('Wrong password') attempts += 1 Display.error('You have exceeded the number of attempts to log in as this user.') sys.exit(1)
cipher = AES.new(hashed, AES.MODE_CBC, aes_iv[:AES.block_size]) return cipher.encrypt(pad(locked_content)) def unlockWithPassword(passkey, encrypted): passkey = hashPhrase(passkey.encode('utf-8'), hashlib.sha256) aes_iv = hashPhrase(passkey, hashlib.sha1) aes = AES.new(passkey,AES.MODE_CBC, aes_iv[:AES.block_size]) decrypted = aes.decrypt(encrypted).decode('utf-8') end_of_json = decrypted.rfind('}') return json.loads(decrypted[:(1+end_of_json)].strip()) while True: password = input('Please enter a short password: '******'{"message": "contents which are not readable"}') break except Exception as msg: Display.warn('This password is too long. Please try again. {0}'.format(msg)) while True: passkey = input('Please verify your password: '******'Correct password. \nContents are "{0}"\n'.format(data['message'])) break except: Display.warn('Incorrect password.\n')
import os, json from pyna.base.Display import Display Display.log('Clean begin.') # Clean Json files json_files = [f for f in os.listdir() if '.json' in f] if len(json_files) > 0: Display.warn('Purging {0} JSON files'.format(len(json_files))) for f in json_files: os.remove(f) # Remove keys json_files = [f for f in os.listdir('config/keys/') if '.pyna' in f] if len(json_files) > 0: Display.warn('Purging {0} Pyna Key files'.format(len(json_files))) for f in json_files: os.remove('config/keys/{0}'.format(f)) # Clean node list Display.warn('Cleaning nodes.json') with open('config/nodes.json','w') as nodelistconfig: json.dump({"nodes": []}, nodelistconfig) # Clean users list Display.warn('Cleaning users.json') with open('config/users.json','w') as users: json.dump({}, users) # Clean log Display.warn('Cleaning log file')
def received(self, msg): emoter = msg['sender']['alias'] if emoter != "": emoter += " " Display.subtle(emoter + msg['message'])