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 unlock(): # 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('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.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) # lock the file result = 'failed' if helper.db_unlock(file_code, server, user_id): result = 'success' return jsonify({'result': result})
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 test_pwd(self, pwd): hashed_pwd = self.hash(pwd) print(f'hash : {hashed_pwd}') if hashed_pwd == expected: self.my_print(decrypt(success, pwd)) return True elif hashed_pwd == not_really_expected: self.my_print(decrypt(hint, pwd)) return False
def checkBalance(self, params): if len(params) != 0: if "TOKEN" in params: wrapData = params['DATA'] splitData = wrapData.split(".") data = helper.decrypt(splitData[0], globalVariable.key, splitData[1]) newStr = re.match("(.*?)}", data).group() newStr= json.loads(newStr) no_rekening = newStr.get("no_rekening") token = newStr.get("token") tokenStatus = Authentication.checkValidToken(self, params['TOKEN']) if tokenStatus[0]["status"] == "success": now = datetime.datetime.now() month = now.month year = now.year sql = 'SELECT no_rekening, SUM(IF(transaction_type="K", balance, 0)) as K, SUM(IF(transaction_type="D", balance, 0)) as D, (SUM(IF(transaction_type="K", balance, 0))-SUM(IF(transaction_type="D", balance, 0))) as saldo, created_date FROM db_kmpay.tbl_transaksi WHERE MONTH(created_date)= %s and YEAR(created_date)=%s AND no_rekening = %s AND status_transaksi = "SUCCESS" GROUP BY no_rekening, MONTH(created_date), YEAR(created_date);' cursorKmPay.execute(sql,([month], [year],[no_rekening])) result = cursorKmPay.fetchall() items = [] for row in result: items.append({'sum_kredit': row[1], 'sum_debit': row[2], 'saldo': row[3]}) if not items: return {'status ':"success",'code': 204, "result":items} else: return {'status ':"success",'code': 200, "result":items[0]} else: return tokenStatus[0] else: return generalNotification.TokenNotAvailable(self) else: return generalNotification.DataNotAvailable(self)
def checkTransactionByPeriod(self, param): if len(param) != 0: if "TOKEN" in param: wrapData = param['DATA'] splitData = wrapData.split(".") data = helper.decrypt(splitData[0], globalVariable.key, splitData[1]) newStr = re.match("(.*?)}", data).group() newStr= json.loads(newStr) no_rekening = newStr.get("no_rekening") start_period = newStr.get("start_period") end_period = newStr.get("end_period") tokenStatus = Authentication.checkValidToken(self, param['TOKEN']) if tokenStatus[0]["status"] == "success": sql = 'SELECT transaksi_id, transaction_type, description, balance, created_date, status_transaksi FROM tbl_transaksi WHERE no_rekening = %s AND created_date BETWEEN %s AND %s;' cursorKmPay.execute(sql,([no_rekening], [start_period], [end_period])) result = cursorKmPay.fetchall() items = [] for row in result: transaction_date = row[4].strftime('%d-%m-%Y') items.append({'id': row[0], 'transaction_type': row[1], 'description': row[2], 'balance': row[3], 'transaction_date': transaction_date, 'transaction_status':row[5]}) return {'status':'success','code': 200, 'result ': items} else: return tokenStatus else: return generalNotification.TokenNotAvailable(self) else: return generalNotification.DataNotAvailable(self)
def topupSaldo(self, param): # insertTblLog = 'INSERT INTO tbl_log_topup topup_id, no_rekening, bank_from, bank_to, balance, status, created_date VALUES (%s, %s, %s, %s, %s, %s, %s, %s)' if len(param) != 0: if "TOKEN" in param: now = datetime.datetime.now() wrapData = param['DATA'] splitData = wrapData.split(".") data = helper.decrypt(splitData[0], globalVariable.key, splitData[1]) newStr = re.match("(.*?)}", data).group() newStr = json.loads(newStr) no_rekening = newStr.get("no_rekening") tokenStatus = Authentication.checkValidToken(self, param['TOKEN']) if tokenStatus[0]["status"] == "success": member_id = getMemberIdbyBankAcc(self, no_rekening) domain = helper.getPrefixDomain(self, newStr.get("domain")) order_number = generateOrderNumber(self, domain['alias']) insertTblTopup = 'INSERT INTO tbl_topup (member_id, order_number, payment_type, total_payment, transaction_time, transaction_status, status_message, created_date, created_by) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)' cursorKmPay.execute(insertTblTopup, ([member_id], [order_number], [globalVariable.payment_type], [newStr.get("amount")], [now], [globalVariable.transaction_status], [globalVariable.topup_status_message], [now], [globalVariable.create_by])) connectKmPay.commit() # INSERT transaksi tabel # insertTblTransaksi = 'INSERT INTO tbl_transaksi (no_rekening, transaction_type, point_type, description, balance, transaksi_date, status_transaksi, created_date, created_by) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)' # a.execute(insertTblTopup, ([no_rekening], ["K"], ['TOPUP'], ["description"], [newStr.get("balance")], [now], ['SUCCESS'], [now], ['1'])) # conn.commit() else: return tokenStatus else: return generalNotification.TokenNotAvailable(self) else: return generalNotification.DataNotAvailable(self)
def createCart(self, param): if len(param) != 0: if "TOKEN" in param: wrapData = param['DATA'] splitData = wrapData.split(".") data = helper.decrypt(splitData[0], globalVariable.key, splitData[1]) data = data.replace("\x08", "") newStr = json.loads(data) member_id = newStr["member_id"] cart_items = newStr["cart_items"] for item in cart_items: qty = item["quantity"] product_detail_id = item["product_detail_id"] subTotal = calculatePriceProductByQty(self, product_detail_id, qty) createCartSql = 'INSERT INTO tbl_cart (member_id, product_detail_id, quantity, price, created_date, created_by) VALUES (%s, %s, %s, %s, %s, %s);' cursorKmStore.execute(createCartSql, ([member_id], [ product_detail_id ], [qty], [subTotal], [now], [globalVariable.create_by])) connectKmStore.commit() else: return generalNotification.TokenNotAvailable(self) else: return generalNotification.DataNotAvailable(self)
def createFile(self, path): absolutePath = absolute(self.path, path) print 'local/update | Creating new file... ' + absolutePath if os.path.exists(absolutePath): print 'local/update | Nothing to create, file already exists: ' + absolutePath return dirPath = os.path.dirname(absolutePath) file = self.box.getItem(path) if file is None: print 'local/update | Cant locate file on Box drive: ' + absolutePath return if not os.path.exists(dirPath): print 'local/update | Parent dir doesnt exists: ' + dirPath self.createDir(dirPath) output = io.BytesIO() file.download_to(output) decrypt(output, absolutePath, self.key) print 'local/update | File creation succeeded: ' + absolutePath
def register(): # retrieve essential information pbk = helper.decrypt(request.headers.get('pbk'), config.AUTHENTICATION_SERVER_PRIVATE_KEY) # register and get user id id = helper.db_register(pbk) # return user id return jsonify({'id': id})
def registerAccount(self, param): if len(param) != 0: if "TOKEN" in param: now = datetime.datetime.now() wrapData = param['DATA'] splitData = wrapData.split(".") data = helper.decrypt(splitData[0], globalVariable.key, splitData[1]) newStr = re.match("(.*?)}", data).group() newStr = json.loads(newStr) email = newStr.get("email") full_name = newStr.get("full_name") address = newStr.get("address") token = newStr.get("token") tokenStatus = Authentication.checkValidToken(self, param['TOKEN']) if tokenStatus[0]["status"] == "success": emailStatus = checkEmailAccount(self, email) prefix_domain = helper.getPrefixDomain(self, newStr.get("domain")) no_rekening = str( prefix_domain['prefix_domain']) + generateAccountBank(self) if emailStatus != 1: now = str(datetime.datetime.now()) createMemberAccountSql = "INSERT INTO tbl_member (member_no_rekening, member_email, full_name, address, member_created_date, member_created_by) VALUES (%s, %s, %s, %s, %s, %s);" cursorKmCrm.execute(createMemberAccountSql, ([no_rekening], [email], [full_name], [ address ], [now], [globalVariable.create_by])) connectKmCrm.commit() # insert into rekening table createAccountSql = 'INSERT INTO tbl_rekening (no_rekening, is_active, activate_date, created_date, created_by) VALUES (%s, %s, %s, %s, %s);' cursorKmCrm.execute(createAccountSql, ([no_rekening], [1], [now], [now], [globalVariable.create_by])) connectKmCrm.commit() return jsonify({ 'status ': "success", 'code': 200, "message": "Create Account Success" }) else: return jsonify({ 'status ': "error", 'code': 204, "message": "Email has been register before" }) else: return tokenStatus else: return generalNotification.TokenNotAvailable(self) else: return generalNotification.DataNotAvailable(self)
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 withdrawSaldo(self, param): if len(param) != 0: if "TOKEN" in param: wrapData = param['DATA'] splitData = wrapData.split(".") data = helper.decrypt(splitData[0], globalVariable.key, splitData[1]) newStr = re.match("(.*?)}", data).group() newStr= json.loads(newStr) no_rekening = newStr.get("no_rekening") type = newStr.get("type") domain = newStr.get("domain") amount = newStr.get("amount") tokenStatus = Authentication.checkValidToken(self, param['TOKEN']) prefix = helper.getPrefixDomain(self, domain) prefix = prefix['prefix_domain'] withdrawNumber = generateWithdrawNumber(self, prefix) withdraw_pin = generatePIN(self) if tokenStatus[0]["status"] == "success" and pinStatus["code"] == 200 : balance = checkBalance(self, param) if balance["result"] != []: lastCredit = balance["result"]["saldo"] saldo = int(lastCredit) - int(amount) if saldo >= 0: withdrawSql = 'INSERT INTO tbl_withdraw (no_rekening, withdraw_number, withdraw_pin, balance, type, status, created_date, created_by) VALUES (%s, %s, %s, %s, %s, %s, %s);' cursorKmPay.execute(withdrawSql, ([no_rekening], [withdrawNumber], [withdraw_pin], [amount], [type], ["PENDING"], [now], [globalVariable.create_by])) connectKmPay.commit() # withdrawSql = 'INSERT INTO tbl_transaksi (no_rekening, transaction_type, description, balance, transaksi_date, status_transaksi, created_date, created_by) VALUES (%s, %s, %s, %s, %s, %s, %s, %s);' # cursorKmPay.execute(withdrawSql, ([no_rekening], ["D"], ["WITHDRAW"], [amount], [now], ["SUCCESS"], [now], [globalVariable.create_by])) # connectKmPay.commit() # Insert to LOG withdrawLogSql = 'INSERT INTO tbl_log_withdraw (no_rekening, withdraw_pin, balance, type, status, created_date, created_by) VALUES (%s, %s, %s, %s, %s, %s, %s);' cursorKmPay.execute(withdrawLogSql, ([no_rekening], [withdraw_pin], [amount], [type], ["NOT RECEIVE"], [now], [globalVariable.create_by])) connectKmPay.commit() return {'status ':"success",'code': 200, "result":"Success Withdraw"} else: return {'status ':"success",'code': 204, "result":"Saldo anda tidak mencukupi"} else: return generalNotification.DataNotAvailable(self) else: return tokenStatus else: return generalNotification.TokenNotAvailable(self) else: return generalNotification.DataNotAvailable(self)
def process_signal(self, signal): """ :param signal: dict type :return: None """ try: from hw_controller import HardwareSignal decrypted_signal = decrypt(signal["message"]) formatted_signal_for_hardware = self.__create_signal_for_hw( decrypted_signal) # Transmit signal to hardware HardwareSignal().transmit(formatted_signal_for_hardware) except DecryptionError: # TODO: Log error while decrypting signal received from cloud. pass except InvalidCloudSignal: # TODO: Log error while concerting cloud signal to command for hardware. pass
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})