def is_locked(): # retrieve essential information data = request.get_json(force=True) user_id = request.headers.get('id') encrypted_file_code = request.headers.get('file_code') encrypted_server_addr = request.headers.get('server') encrypted_tmp_pvk = request.headers.get('access_key') ticket = request.headers.get('security_check') # validate the ticket and fail the request if validation failed, this ensure the client is authorized by auth server if helper.decrypt(ticket, config.LOCK_SERVER_PRIVATE_KEY) != config.AUTHENTICATION_SERVER_PUBLIC_KEY: return None # decrypt the encrypted_key with the temporary public key # this helps client to ensure we are the right directory server, not man-in-middle tmp_pvk = helper.decrypt(encrypted_tmp_pvk, config.LOCK_SERVER_PRIVATE_KEY) file_code = helper.decrypt(encrypted_file_code, tmp_pvk) server = helper.decrypt(encrypted_server_addr, tmp_pvk) print(list(helper.db_get_lock(file_code, server))) # return the result lock = helper.db_get_lock(file_code, server) locked = 'False' locker = '' if helper.db_get_lock(file_code, server).count() > 0: locked = ' True' locker = lock[0]['uid'] return jsonify({'locked': helper.encrypt(locked, tmp_pvk), 'locker': helper.encrypt(locker, tmp_pvk)})
def assign_upload_directory(): # retrieve essential information data = request.get_json(force=True) user_id = request.headers.get('id') encrypted_file_name = request.headers.get('filename') encrypted_tmp_pvk = request.headers.get('access_key') ticket = request.headers.get('ticket') # validate the ticket and fail the request if validation failed, this ensure the client is authorized by auth server if helper.decrypt(ticket, config.DIRECTORY_SERVER_PRIVATE_KEY ) != config.AUTHENTICATION_SERVER_PUBLIC_KEY: return None # decrypt the encrypted_key with the temporary public key # this helps client to ensure we are the right directory server, not man-in-middle tmp_pvk = helper.decrypt(encrypted_tmp_pvk, config.DIRECTORY_SERVER_PRIVATE_KEY) file_name = helper.decrypt(encrypted_file_name, tmp_pvk) """ We will make every file server have a copy of the file """ if helper.db_get_directories(file_name).count() > 0: # if file already exists, send back the old directory and old file will be replaced directories = helper.db_get_directories(file_name) encrypted_file_code = helper.encrypt(directories[0]['file_code'], tmp_pvk) encrypted_destinations = [] for directory in directories: encryted_directory = helper.encrypt( directory['fs_host'] + ':' + directory['fs_port'], tmp_pvk) encrypted_destinations.append(encryted_directory) else: # generate a file code, this is the name of the file in the actual file server # encrypt the file code with the tmp pbk file_code = "file{}.{}".format(helper.directory_table().count(), file_name.split('.')[-1]) encrypted_file_code = helper.encrypt(file_code, tmp_pvk) # generate the diretory list and add them to record encrypted_destinations = [] for i in config.FILE_SERVER_PORT: # add the directory record into db helper.db_insert_single_directory(file_name, file_code, i, config.FILE_SERVER_HOST[i], config.FILE_SERVER_PORT[i]) # append encrypted directories to the returning list destination = config.FILE_SERVER_HOST[ i] + ":" + config.FILE_SERVER_PORT[i] encrypted_destination = helper.encrypt(destination, tmp_pvk) encrypted_destinations.append(encrypted_destination) # return the response return jsonify({ 'code': encrypted_file_code, 'destinations': encrypted_destinations })
def local(self, directoryPath): print("Local indexing started...") for root, dirnames, filenames in os.walk(directoryPath): for filename in filenames + dirnames: fullFilename = os.path.join(root, filename) if os.path.isdir(fullFilename): self.localDirs.append( FileIndex(filename, normalize(root), '', True)) else: output = io.BytesIO() encrypt(fullFilename, output, self.key) self.localFiles.append( FileIndex(filename, normalize(root), sha1(output))) print("Local indexing finished.")
def register(pbk): headers = { 'pbk': helper.encrypt(pbk, config.AUTHENTICATION_SERVER_PUBLIC_KEY) } response = requests.post(config.AUTHENTICATION_SERVER_REGISTER_REQUEST, data=json.dumps(""), headers=headers) return json.loads(response.text)['id']
def update(self, path): relativePath = relative(self.path, path) print 'remote/update | Updating file... ' + relativePath file = self.box.getItem(relativePath) if file is None: print 'remote/update | Cant locate file on Box drive: ' + relativePath self.createFile(relativePath) return try: output = io.BytesIO() encrypt(path, output, self.key) if file.sha1 == sha1(output): print 'remote/update | File already up to date: ' + relativePath return file.update_contents_with_stream(output) except (IOError, OSError): print 'remote/update | Cant find local file or is blocked: ' + relativePath return print 'remote/update | File updating succeeded: ' + relativePath
def transmit_signal(self, signal): """ It encrypts the Signal and then transmit over a respective channel. :param signal: signal to transmit :return: None """ if not signal: raise ValueError("Invalid signal inputted.") from helper import encrypt_signal_for_cloud as encrypt self.__cloud_client = CloudClient(name="Cloud_Tx", mode="SEND") self.__cloud_client.transmit(encrypt(signal))
def createFile(self, path): relativePath = relative(self.path, path) print 'remote/update | Creating new file... ' + relativePath file = self.box.getItem(relativePath) if file is not None: print 'remote/update | File already exists on Box: ' + relativePath return fileName = os.path.basename(relativePath) dirPath = os.path.dirname(relativePath) dir = self.box.getItem(dirPath) if dir is None: print 'remote/update | Parent dir doesnt exists: ' + dirPath dir = self.createDir(dirPath) try: output = io.BytesIO() encrypt(path, output, self.key) dir.upload_stream(output, fileName) except (IOError, OSError): print 'remote/update | Cant find local file: ' + relativePath return print 'remote/update | File creation succeeded: ' + relativePath
def assign_download_directory(): # retrieve essential information data = request.get_json(force=True) user_id = request.headers.get('id') encrypted_file_name = request.headers.get('filename') encrypted_tmp_pvk = request.headers.get('access_key') ticket = request.headers.get('ticket') # validate the ticket and fail the request if validation failed, this ensure the client is authorized by auth server if helper.decrypt(ticket, config.DIRECTORY_SERVER_PRIVATE_KEY ) != config.AUTHENTICATION_SERVER_PUBLIC_KEY: return None # decrypt the encrypted_key with the directory server's public key # this helps client to ensure we are the right directory server, not man-in-middle tmp_pvk = helper.decrypt(encrypted_tmp_pvk, config.DIRECTORY_SERVER_PRIVATE_KEY) file_name = helper.decrypt(encrypted_file_name, tmp_pvk) """ We will return all the directory possible, client may pick the one that is available(e.g unlock) the directory information will be encrypted by tmp pvk generated by the auth server """ directories = helper.db_get_directories(file_name) encrypted_file_code = helper.encrypt(directories[0]['file_code'], tmp_pvk) encryped_directories = [] for directory in directories: encryted_directory = helper.encrypt( directory['fs_host'] + ':' + directory['fs_port'], tmp_pvk) encrypted_fs_id = helper.encrypt(directory['fs_id'], tmp_pvk) encryped_directories.append(encryted_directory) # return the response return jsonify({ 'code': encrypted_file_code, 'directories': encryped_directories })
def updateFile(self, path): absolutePath = absolute(self.path, path) if not os.path.exists(absolutePath): self.createFile(path) return print 'local/update | Updating file... ' + absolutePath file = self.box.getItem(path) if file is None: print 'local/update | Cant locate file on Box drive: ' + absolutePath return try: output = io.BytesIO() encrypt(absolutePath, output, self.key) if file.sha1 == sha1(output): print 'local/update | File already up to date: ' + absolutePath return output = io.BytesIO() file.download_to(output) decrypt(output, absolutePath, self.key) print 'local/update | File updating succeeded: ' + absolutePath except (IOError, OSError) as e: print e.errno print e print 'local/update | Can\'t open local file: ' + absolutePath
def register(): if request.method == 'GET': return render_template('register.html') else: username = request.form.get('username') email = request.form.get('email') password = request.form.get('password') repeat = request.form.get('repeat') user = User.query.filter_by(email=email).first() if user: flash('Пользователь с такой почтой уже существует') return redirect('/register') if password != repeat: flash('Введенные пароли не совпадают') return redirect('/register') new_user = User(email=email, username=username, password=encrypt(password)) db.session.add(new_user) db.session.commit() return redirect('/login')
data['phone']) checkPersonValues = (data['email']) try: cursor.execute(checkPersonSQL, checkPersonValues) if cursor.rowcount != 0: print("Status: 420 Email Already Exist\n") exit(1) else: cursor.close() try: cursor = connection.cursor() cursor.execute(addPersonSQL, addPersonValues) personPk = cursor.lastrowid hashed, salt = encrypt(data['password']) addPasswordValues = (personPk, hashed, salt, data['phone_type']) cursor.execute(addPasswordSQL, addPasswordValues) connection.commit() print("Status: 200 OK\n") except Exception as e: connection.rollback() print("Status: 400 Error Signing up\n") print e exit(1) except Exception as e: connection.rollback() print("Status: 400 Invalid Request\n") print e
def lock_or_unlock(fname, lock): """ :param fname: :param uid: :param lock: :return: """ """ Get the registration information of the client """ info = helper.db_get_registration_info() client_private_key = info['pvk'] uid = info['id'] """ Communicating with Authentication Server, get ticket for directory server """ # authenticate client to get access to the directory server directory_server = helper.encrypt("directory", client_private_key) encrypted_auth_server_pbk = helper.encrypt( config.AUTHENTICATION_SERVER_PUBLIC_KEY, client_private_key) headers = { 'id': uid, 'server': directory_server, 'security_check': encrypted_auth_server_pbk } response = requests.post(config.AUTHENTICATION_SERVER_GET_TICKET_REQUEST, data=json.dumps(""), headers=headers) # parse respones data json_data = json.loads(response.text) # decrypt the pbk and use it to encrypt sensitive information encrypted_client_tmp_pbk = json_data['client'] encrpyted_directory_sever_tmp_pvk = json_data['server'] ticket = json_data['ticket'] client_tmp_pbk_for_directory_server = helper.decrypt( encrypted_client_tmp_pbk, client_private_key) """ Communicating with Directory Server: request directory server for all the file server(s) holding the file directory server will return back a number of file servers and Client is required to distribute the files across these servers security: the Client's uid, Client's public key will be encrypted with directory server's public key directory server will then decrypt Client's public key and use it to encrypt the target file servers address the encrypted address will then be sent back this ensures man-in-middle will not be able to pretend to be the directory server and MAKE CLIENT UPLOAD FILES TO SPY SERVER """ # encrypt file name with client tmp public key secure_fname = helper.encrypt(fname, client_tmp_pbk_for_directory_server) headers = { 'id': uid, 'filename': secure_fname, 'access_key': encrpyted_directory_sever_tmp_pvk, 'ticket': ticket } response = requests.post( config.DIRECTORY_SERVER_DOWNLOAD_DESTINATION_ASSIGNING_REQUEST, data=json.dumps({}), headers=headers) # parse respones data json_data = json.loads(response.text) # parse and decrypt response, the target file server's address is stored in header # file will use file code as the file name is distributed file system encrypted_download_directories = json_data['directories'] file_code = helper.decrypt(json_data['code'], client_tmp_pbk_for_directory_server) """ Communicating with Authentication Server, get ticket and lock the file: """ while True: for encrypted_directory in encrypted_download_directories: # decrypt the destination directory = helper.decrypt(encrypted_directory, client_tmp_pbk_for_directory_server) # get ticket from auth server secure_file_server = helper.encrypt(directory, client_private_key) encrypted_auth_server_pbk = helper.encrypt( config.AUTHENTICATION_SERVER_PUBLIC_KEY, client_private_key) headers = { 'id': uid, 'server': secure_file_server, 'security_check': encrypted_auth_server_pbk } response = requests.post( config.AUTHENTICATION_SERVER_GET_TICKET_REQUEST, data=json.dumps({}), headers=headers) # parse respones data json_data = json.loads(response.text) # decypt keys and ticket fs_tmp_pvk = json_data['server'] ticket = json_data['ticket'] client_tmp_pbk_for_file_server = helper.encrypt( json_data['client'], client_private_key) # encrypt data with client tmp public key secure_file_code = helper.encrypt(file_code, client_tmp_pbk_for_file_server) secure_directory = helper.encrypt(directory, client_tmp_pbk_for_file_server) # send the file headers = { 'id': uid, 'file_code': secure_file_code, 'server': secure_directory, 'access_key': fs_tmp_pvk, 'ticket': ticket } if lock: response = requests.post(config.LOCK_REQUEST.format(directory), data=json.dumps({}), headers=headers) if json.loads(response.text)['result'] == 'failed': print( "Locking Failed. Locking will restart after 5 minutes. It you do not want to wait, you can terminate the application by pressing ctrl+c." ) helper.wait_for_while(300) print("Locking restart.") break else: response = requests.post( config.UNLOCK_REQUEST.format(directory), data=json.dumps({}), headers=headers) print(json.loads(response.text)) if json.loads(response.text)['result'] == 'failed': print( "Unocking Failed. Locking will restart after 5 minutes. It you do not want to wait, you can terminate the application by pressing ctrl+c." ) helper.wait_for_while(300) print("Unocking restart.") break if encrypted_directory == encrypted_download_directories[-1]: print("Locking Successful. File is locked") return True
def secure_download(fname): """ :param fname: :return: """ """ Get the registration information of the client """ info = helper.db_get_registration_info() client_private_key = info['pvk'] uid = info['id'] """ Try to get file directories, before we do it, we check if the file directory is cached if yes, then we simply use it """ if fname not in directory_cache: """ Communicating with Authentication Server, get ticket for directory server """ # get ticket directory_server = helper.encrypt("directory", client_private_key) encrypted_auth_server_pbk = helper.encrypt( config.AUTHENTICATION_SERVER_PUBLIC_KEY, client_private_key) headers = { 'id': uid, 'server': directory_server, 'security_check': encrypted_auth_server_pbk } response = requests.post( config.AUTHENTICATION_SERVER_GET_TICKET_REQUEST, data=json.dumps({}), headers=headers) # parse respones data json_data = json.loads(response.text) # decrypt the pbk and use it to encrypt sensitive information encrypted_client_tmp_pbk = json_data['client'] encrpyted_directory_sever_tmp_pvk = json_data['server'] ticket = json_data['ticket'] client_tmp_pbk_for_directory_server = helper.decrypt( encrypted_client_tmp_pbk, client_private_key) """ Communicating with Directory Server: request directory server for destination file server(s) directory server will return back a number of file servers and Client is required to distribute the files across these servers security: the Client's uid, Client's public key will be encrypted with directory server's public key directory server will then decrypt Client's public key and use it to encrypt the target file servers address the encrypted address will then be sent back this ensures man-in-middle will not be able to pretend to be the directory server and MAKE CLIENT UPLOAD FILES TO SPY SERVER """ # encrypt file name with client tmp public key secure_fname = helper.encrypt(fname, client_tmp_pbk_for_directory_server) headers = { 'id': uid, 'filename': secure_fname, 'access_key': encrpyted_directory_sever_tmp_pvk, 'ticket': ticket } response = requests.post( config.DIRECTORY_SERVER_DOWNLOAD_DESTINATION_ASSIGNING_REQUEST, data=json.dumps({}), headers=headers) # parse respones data json_data = json.loads(response.text) # parse and decrypt response, the target file server's address is stored in header # file will use file code as the file name is distributed file system encrypted_download_directories = json_data['directories'] file_code = helper.decrypt(json_data['code'], client_tmp_pbk_for_directory_server) """ Cache the file directory """ cache_directory(fname, file_code, encrypted_download_directories, client_tmp_pbk_for_directory_server) else: """ Use the file directory cache """ file_code = directory_cache[fname][0] encrypted_download_directories = directory_cache[fname][1] client_tmp_pbk_for_directory_server = directory_cache[fname][2] """ Start download the file """ while True: for directory in encrypted_download_directories: # decrypt the destination directory = helper.decrypt(directory, client_tmp_pbk_for_directory_server) """ Communicating with Authentication Server, get ticket for lock checking: """ # get ticket from auth server encrypted_auth_server_pbk = helper.encrypt( config.AUTHENTICATION_SERVER_PUBLIC_KEY, client_private_key) headers = { 'id': uid, 'server': 'locking', 'security_check': encrypted_auth_server_pbk } response = requests.post( config.AUTHENTICATION_SERVER_GET_TICKET_REQUEST, data=json.dumps({}), headers=headers) # parse respones data json_data = json.loads(response.text) # decypt keys and ticket sever_tmp_pvk = json_data['server'] ticket = json_data['ticket'] client_tmp_pbk_for_locking_server = helper.encrypt( json_data['client'], client_private_key) """ Communicating with Locking Server, check if the file is locked in the given destination """ # check if the file has been locked secure_file_server = helper.encrypt(directory, client_private_key) headers = { 'id': uid, 'server': secure_file_server, 'security_check': ticket, 'access_key': sever_tmp_pvk } response = requests.post(config.ISLOCK_REQUEST, data=json.dumps({}), headers=headers) # parse respones data json_data = json.loads(response.text) # decypt keys and ticket locked = helper.decrypt(json_data['locked'], client_tmp_pbk_for_locking_server) locker = helper.decrypt(json_data['locker'], client_tmp_pbk_for_locking_server) if not locked == 'True' or locker == uid: """ Download the file """ """ Communicating with Authentication Server, get ticket for file uploading: """ # get ticket from auth server secure_file_server = helper.encrypt(directory, client_private_key) encrypted_auth_server_pbk = helper.encrypt( config.AUTHENTICATION_SERVER_PUBLIC_KEY, client_private_key) headers = { 'id': uid, 'server': secure_file_server, 'security_check': encrypted_auth_server_pbk } response = requests.post( config.AUTHENTICATION_SERVER_GET_TICKET_REQUEST, data=json.dumps({}), headers=headers) # parse respones data json_data = json.loads(response.text) # decypt keys and ticket fs_tmp_pvk = json_data['server'] ticket = json_data['ticket'] client_tmp_pbk_for_file_server = helper.encrypt( json_data['client'], client_private_key) # encrypt data with client tmp public key secure_file_code = helper.encrypt( file_code, client_tmp_pbk_for_file_server) """ Download the file """ # download the file headers = { 'id': uid, 'file_code': secure_file_code, 'access_key': fs_tmp_pvk, 'ticket': ticket } response = requests.post( config.DOWNLOAD_FILE_REQUEST.format(directory), data=json.dumps({}), headers=headers) # return the file encrypted_data = response.content data = helper.decrypt(encrypted_data, client_tmp_pbk_for_file_server) return data """ if all the destination are locked, then the file must be locked, wait for 5 minute and try again """ print( "File is locked. Download will restart after 5 minutes. It you do not want to wait, you can terminate the application by pressing ctrl+c." ) helper.wait_for_while(300) print("Upload restart.")
def generate_ticket(): # retrieve essential information user_id = request.headers.get('id') encrypted_server = request.headers.get('server') security_check = request.headers.get('security_check') client_pbk = config.CLIENT_PUBLIC_KEY[user_id] # find out the server public key based on the request server = helper.decrypt(encrypted_server, client_pbk) if server == "directory": fs_pbk = config.DIRECTORY_SERVER_PUBLIC_KEY elif server == "locking": fs_pbk = config.DIRECTORY_SERVER_PUBLIC_KEY elif server == "transaction": fs_pbk = config.DIRECTORY_SERVER_PUBLIC_KEY else: # find file server id based on addr server = helper.decrypt(encrypted_server, client_pbk) for key in config.FILE_SERVER_PORT: if server == config.FILE_SERVER_HOST[key] + ':' + config.FILE_SERVER_PORT[key]: fs_pbk = config.FILE_SERVER_PUBLIC_KEY[key] break """ Security Check, on the authentication server side, we do need to worry about the fake Client issue. To make authetication server trust our request, we upload the encrypted public key of auth server(encrypted with client's private key), the authentication server will decrypt(with out client's public key) and compare the public key This ensures the client - has auth server's public key - has target client's private key """ security_check = helper.decrypt(security_check, client_pbk) if not security_check == config.AUTHENTICATION_SERVER_PUBLIC_KEY: # client didn't encrypt auth server's public key with it's private key # Hence, the client could be man-in-middle # Hence reject the request return None else: """ Generate the public key and private key pair Public key: - will be hold by the client. - Hence, encrypt it with client's public key - Client needs to decrupt it with it's private key Private key: - will be hold by the target server - Hence, encrypt it with server's public key The key pair will be used to encrypt/decrypt the sensitive data during the data transferring between client and target server **The auth server will encrypt it's public key with the target server's public key, this is used as the security check for the directory server. **This makes the directory server trust the client and we call this security check TICKET """ (tmp_pbk, tmp_pvk) = helper.generate_ticket() encrypted_pbk = helper.encrypt(tmp_pbk, client_pbk) encrypted_pvk = helper.encrypt(tmp_pvk, fs_pbk) security_check = helper.encrypt(config.AUTHENTICATION_SERVER_PUBLIC_KEY, fs_pbk) return jsonify({'client': encrypted_pbk, 'server': encrypted_pvk, 'ticket': security_check})