def authenticate(username, port_no): # Authenticating file server conn = create_connection() c = conn.execute('Select * from SERVICE_DATA where SERVICE_ID = ?', (username, )) res = c.fetchone() #print(res) if (res == None): conn.execute('insert into SERVICE_DATA VALUES(?,?,?,?,?)', (str(username), str(crypto.get_key()), 1, 0, port_no)) conn.commit() c = conn.execute('select * from SERVICE_DATA where SERVICE_ID=?', (username, )) # for x in c: # print(x) res1 = c.fetchone() conn.close() return True, res1[1] else: conn.close() return True, res[1]
def handle_request(arg_dict, key_index): error = 'message error!' if arg_dict.has_key('id'): if arg_dict.has_key('size') and arg_dict.has_key('md5'): # filter if arg_dict['id'].isdigit() and arg_dict['size'].isdigit() and arg_dict['md5'].isalnum() and check_id( arg_dict['id']): if info_cache.has_key(arg_dict['id']): for item in info_cache[arg_dict['id']]: if item['size'] == arg_dict['size'] and item['md5'] == arg_dict['md5']: item['count'] += 1 if item['count'] > TRUST_VALUE: if new_upload_tasks(arg_dict['id'], item['size'], item['md5']): info_cache.pop(arg_dict['id']) else: info_cache[arg_dict['id']].append( dict({'size': arg_dict['size'], 'md5': arg_dict['md5'], 'count': 1})) else: info_cache[arg_dict['id']] = [] info_cache[arg_dict['id']].append( dict({'size': arg_dict['size'], 'md5': arg_dict['md5'], 'count': 1})) return 'OK' return error elif arg_dict['id'].isdigit(): count, upload_path = get_upload_info(arg_dict['id']) if upload_path is not None and count is not None: return response_with_cookie(count, upload_path, key_index) else: return crypto.encrypt('boot_info', crypto.get_key(key_index)) else: return error
def response_with_cookie(offset, upload_path, key_index): while True: cookie = cookie_generator(24) if session_info_db.query_one({'_id': ObjectId(cookie)}) is None: break res = crypto.encrypt('boot_skip=%d&cookie=%s' % (offset, cookie), crypto.get_key(key_index)), cookie_info_db.insert({'_id': ObjectId(cookie), 'upload_path': upload_path}) return res
def handle_connection_request(user_request, connection, client_addr): # Handles Specific Request to obtain session key for a particular server user_id = user_request[constants.USER_ID] # Check in database if user id exists conn = database_init() crs = conn.cursor() c = crs.execute('Select * from CLIENT_DATA where USER_ID =?', (user_id, )) res = c.fetchone() if (res == None): print("USER ID doesn't exist") data = {} data[constants.STATUS] = False conn.close() else: service_id = user_request[constants.SERVICE_ID] crs = conn.cursor() c = crs.execute('Select * from SERVICE_DATA where SERVICE_ID =?', (service_id, )) res1 = c.fetchone() if (res1 == None): data = {} data[constants.STATUS] = False conn.close() else: data = {} data[constants.STATUS] = True conn.close() # Getting Keys client_key = res[2] session_key = crypto.get_key() service_key = res1[1] # Creating Response server_response = create_server_response(session_key, client_key) service_ticket = create_service_ticket(user_id, service_id, session_key, service_key, client_addr) data[constants.SERVER_RESPONSE] = server_response data[constants.SERVICE_TICKET] = service_ticket # Sending Response data_stream = crypto.serial(data) connection.send(data_stream) print("Responded to ", user_id)
def consume_single_playlist(playlist, m3u8_uri, destination_path, encrypt=False): full_path = build_full_path(destination_path, m3u8_uri) if encrypt: key_name = crypto.get_key_name(m3u8_uri) new_key = crypto.get_key(key_name, full_path) else: new_key = encrypt downloaded_key = download_key(playlist, full_path, new_key) downloaded_segments = download_segments(playlist, full_path, new_key) m3u8_has_changed = downloaded_key or any(downloaded_segments) if m3u8_has_changed: save_m3u8(playlist, m3u8_uri, full_path, new_key) return filter(None, downloaded_segments) return False
def collect(): error = 'error!' key_index = None data = None if request.method == 'POST': print 'form : %s' % request.form agent = request.headers.get('User-Agent') if agent and agent != "29bd7da7271b5515f402128c8f5c5377": return error key = request.cookies.get('key') if key: print 'key is %s' % key message = check_session(str(key)) # for test only # key_index = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f' else: return 'Key error' if message is not None: key_index = message else: upload_path = check_cookie(str(key)) if upload_path is not None and request.files.has_key('file'): print 'receive file %s' % request.files return handle_upload_file(request.files['file'], upload_path) if key_index is None: return 'no key_index!!!' if len(request.form) > 0: data = crypto.decrypt(unhexlify(request.form['data']), crypto.get_key(key_index)) arg_list = data.split('&') arg_dict = {} for i in arg_list: g = i.split('=') if g and len(g) == 2: arg_dict[g[0]] = g[1] return handle_request(arg_dict, key_index) return 'fatal error'
def Main(): global cryptokeys, bitcommits, selfcommit, pseudonym, server_session_key, client_keys, server_pub_key, play_order with open('server_public_key', 'rb') as kf: server_pub_key = serialization.load_pem_public_key( kf.read(), default_backend()) global s s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((addr, port)) except ConnectionRefusedError: print("Error! The server is not online!") return server_session_key, iv, dh_a = server_handshake() crypto.init(crypto.get_bytes(iv)) signature = b'' cert_pem = b'' if not test: pkcs11 = PyKCS11.PyKCS11Lib() if path.exists("/usr/local/lib/libpteidpkcs11.so"): pkcs11.load('/usr/local/lib/libpteidpkcs11.so') else: pkcs11.load('/usr/lib/libpteidpkcs11.so') slots = pkcs11.getSlotList() found_cc = False for slot in slots: if 'CARTAO DE CIDADAO' in pkcs11.getTokenInfo(slot).label: found_cc = True session = pkcs11.openSession(slot) privKey = session.findObjects([ (CKA_CLASS, CKO_PRIVATE_KEY), (CKA_LABEL, 'CITIZEN AUTHENTICATION KEY') ])[0] certificate = session.findObjects( template=[(PyKCS11.CKA_LABEL, "CITIZEN AUTHENTICATION CERTIFICATE" ), (PyKCS11.CKA_CLASS, PyKCS11.CKO_CERTIFICATE)])[0] all_attr = [ e for e in list(PyKCS11.CKA.keys()) if isinstance(e, int) ] attr = session.getAttributeValue(certificate, all_attr) attr = dict(zip(map(PyKCS11.CKA.get, all_attr), attr)) cert_der = x509.load_der_x509_certificate( bytes(attr['CKA_VALUE']), default_backend()) cert_pem = cert_der.public_bytes(Encoding.PEM) while True: pseudonym = 'steve' + str(randint(00000000, 99999999)) send({ 'type': messages.REGISTER_REQUEST, 'sig': bytes( session.sign(privKey, bytes(pseudonym, 'utf-8'), Mechanism(CKM_SHA1_RSA_PKCS))).hex(), 'name': pseudonym }) data = receive() if data['type'] != messages.REGISTER_REPLY: raise UnexpectedMessageException() if data['accepted']: break session.closeSession() if not found_cc: print("\nNo citizenship card connected") return # If Test mode is enabled else: while True: pseudonym = 'steve' + str(randint(00000000, 99999999)) send({ 'type': messages.REGISTER_REQUEST, 'sig': signature.hex(), 'name': pseudonym }) data = receive() if data['type'] != messages.REGISTER_REPLY: raise UnexpectedMessageException() if data['accepted']: break print("Hi I am {}".format(pseudonym)) while True: try: print("Starting new game...") cryptokeys = {} # Ci: Ki bitcommits = {} selfcommit = None client_keys = None play_order, client_keys = clients_handshake(dh_a) numPlayers = len(play_order) data = receive() if data['type'] != messages.RANDOMIZATION_REQUEST: raise UnexpectedMessageException() # --- ENCRYPTION/RANDOMIZATION new_tiles = [] for i, tile in enumerate(data['tiles']): if not isinstance(tile, str): tile = crypto.get_string(str(tile).encode('utf-8')) btile = crypto.get_bytes(tile) collision = True key = None while collision: key = crypto.get_key() cr = crypto.encrypt(btile, key) collision = cr in cryptokeys cryptokeys[cr] = key data['tiles'][i] = crypto.get_string(cr) secret_s = secrets.SystemRandom() secret_s.shuffle(data['tiles']) hand_size = data['tile_num'] final_stocksize = len(data['tiles']) - numPlayers * hand_size next_player = play_order[(play_order.index(pseudonym) + 1) % numPlayers] players_without_self = play_order.copy() players_without_self.pop(players_without_self.index(pseudonym)) randomization_reply = { 'type': messages.RANDOMIZATION_REPLY, 'tiles': data['tiles'] } send(randomization_reply) pseudo_hand = [] data = receive() setup = True # --- SELECTION while setup: if data['type'] != messages.ROUTING and data[ 'type'] != messages.SELECTION_REQUEST and data[ 'type'] != messages.SELECTION_END: raise UnexpectedMessageException() else: if data['type'] == messages.SELECTION_END: if len(pseudo_hand) < hand_size: print( "\nSelection ended before hand was complete. Deck distribution cheating occured!" ) send({'type': messages.COMPLAIN, 'cheater': None}) data = receive() else: setup = False send({'type': messages.OK}) break else: tiles = [] picked = [] if data['type'] == messages.ROUTING: if data['data']['type'] != messages.SELECTION_REPLY: raise UnexpectedMessageException() tiles = data['data']['tiles'] picked = data['data']['picked'] else: tiles = data['tiles'] picked = data['picked'] if len(tiles) == final_stocksize or ( randint(0, 99) < prob_deck_cheating and randint(0, 99) < 50 ): # second randint servers to have even smaller probability action = randint(0, 99) if (action < prob_select_end): setup = False selection_end = { 'type': messages.SELECTION_REPLY, 'tiles': tiles, 'picked': picked } send(selection_end) break action = randint(0, 99) if action < prob_pick_tile and len( pseudo_hand) < hand_size: tile_choice = randint(0, len(tiles) - 1) pic_tile = tiles.pop(tile_choice) pseudo_hand.append(pic_tile) picked.append(pic_tile) else: action = randint(0, 99) if action < prob_swap_tiles and len( pseudo_hand) > 0: number_of_swaps = randint(1, len(pseudo_hand)) for i in range(number_of_swaps): tile_choice = randint(0, len(tiles) - 1) temp_tile = pseudo_hand.pop(i) picked.remove(temp_tile) pic_tile = tiles.pop(tile_choice) pseudo_hand.insert(i, pic_tile) picked.append(pic_tile) tiles.insert(tile_choice, temp_tile) player_selection = randint( 0, len(players_without_self) - 1) selection_reply = { 'type': messages.ROUTING, 'destination': players_without_self[player_selection], 'data': { 'type': messages.SELECTION_REPLY, 'tiles': tiles, 'picked': picked } } send(selection_reply) data = receive() # --- COMMIT index_hand = pseudo_hand.copy() while len(bitcommits) < numPlayers: data = receive() if data['type'] == messages.COMMIT_REQUEST: selfcommit = commit(pseudo_hand) send({ 'type': messages.COMMIT_REPLY, 'commit': selfcommit, 'sig': rsa_priv.sign( hashlib.sha256(bytes.fromhex(selfcommit)).digest(), padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()).hex() }) stock = data['stock'] pseudo_hand = [ crypto.get_bytes(data['deck'][t_ix]) for t_ix in pseudo_hand ] bitcommits[str(pseudonym)] = None #self commit print("Sent my bit commitment {}".format(selfcommit)) elif data['type'] == messages.COMMIT_FORWARD: bitcommits[play_order[data['player']]] = data['commit'] print("Received bit commitment {} from player {}".format( data['commit'], play_order[data['player']])) send({'type': messages.OK}) else: raise UnexpectedMessageException() for i, t in enumerate(stock): stock[i] = crypto.get_bytes(t) # --- DECRYPTION new_crypts = {} while True: data = receive() if data['type'] != messages.REVELATION_REQUEST: raise UnexpectedMessageException() if data['reveal']: to_send = {} for tile, key in cryptokeys.items(): if (new_crypts != {} and tile in new_crypts.values( )) or ( new_crypts == {} and tile not in stock ): # if first to decrypt, tile not in stock, else new_crypts has stuff in it t_str = crypto.get_string(tile) k_str = crypto.get_string(key) to_send[t_str] = k_str for i, tile in enumerate(pseudo_hand): dec = crypto.decrypt(tile, cryptokeys[tile]) pseudo_hand[i] = dec send({'type': messages.REVELATION_REPLY, 'keys': to_send}) else: new_crypts = {} for crypt, key in data['keys'].items(): crypt = crypto.get_bytes(crypt) key = crypto.get_bytes(key) dec = crypto.decrypt(crypt, key) new_crypts[crypt] = dec try: ix = pseudo_hand.index(crypt) pseudo_hand[ ix] = dec # client uses received keys to "decrypt" hand except ValueError as e: pass send({'type': messages.OK}) if data['end']: break pseudo_hand = [ ast.literal_eval(t.decode('utf-8')) for t in pseudo_hand ] # --- DE-ANON de_anon = True my_private_keys = [] #missing_keys = [t[1] for t in pseudo_hand] missing_keys = index_hand.copy() while de_anon: data = receive() if data['type'] == messages.DE_ANON_REQUEST: break elif data['type'] != messages.ROUTING and data[ 'type'] != messages.DE_ANON_PREP_REQUEST: raise UnexpectedMessageException() else: key_array = [] if data['type'] == messages.ROUTING: if data['data']['type'] != messages.DE_ANON_PREP_REPLY: raise UnexpectedMessageException() key_array = data['data']['array'] else: key_array = data['array'] if key_array.count('0' * 852) <= final_stocksize: action = randint(0, 99) if action < prob_end_deanon: selection_reply = { 'type': messages.DE_ANON_PREP_REPLY, 'array': key_array } send(selection_reply) continue action = randint(0, 99) if action < prob_add_keys and len(missing_keys) > 0: key_choice = randint(0, len(missing_keys) - 1) chosen_key = missing_keys.pop(key_choice) key_array.pop(chosen_key) priv_key, pub_key = crypto.generate_RSA_keys() my_private_keys.append([chosen_key, priv_key]) key_array.insert(chosen_key, pub_key.hex()) cheating_key = randint(0, 27) if randint( 0, 99) < prob_deck_cheating and cheating_key not in ( [a[0] for a in my_private_keys] + missing_keys): priv_key, pub_key = crypto.generate_RSA_keys() key_array.pop(cheating_key) key_array.insert(cheating_key, pub_key.hex()) player_selection = randint(0, len(players_without_self) - 1) selection_reply = { 'type': messages.ROUTING, 'destination': players_without_self[player_selection], 'data': { 'type': messages.DE_ANON_PREP_REPLY, 'array': key_array } } send(selection_reply) if data['type'] != messages.DE_ANON_REQUEST: raise UnexpectedMessageException() encrypted_deck = data['array'] current_hand = [] ki_values = [] try: for i in range(len(my_private_keys)): tmp = ast.literal_eval(my_private_keys[i][1].decrypt( bytes.fromhex(encrypted_deck[my_private_keys[i][0]]), padding.OAEP(padding.MGF1(hashes.SHA256()), hashes.SHA256(), None)).decode('utf-8')) ki_values.append(tmp[0]) current_hand.append(tmp[1]) # Verify hand for i in range(len(current_hand)): try: pseudo = h(ki_values[i], current_hand[i]) except: ValueError() if pseudo not in [a[0] for a in pseudo_hand]: raise ValueError() except ValueError: print( "\nCould not de-anonimize deck. Deck distribution cheating occured!" ) send({'type': messages.COMPLAIN, 'cheater': None}) data = receive() send({'type': messages.OK}) game = Logic(numPlayers, hand_size) drawing = False drawn_tile = None stock_empty = len(stock) <= 0 option = 0 while True: data = receive() if data['type'] == messages.CONFIRM_ACTION: #Send OK, opponent played if data['action']['ac'] == 'draw': rec_tile = crypto.get_bytes(data['action']['tile']) send({'type': messages.OK}) stock.remove(rec_tile) drawProcess(False, rec_tile) stock_empty = len(stock) <= 0 else: print( "Opponent", play_order[data['player']], "played", str(data['action']['tile']) + "!") if data['action']['ac'] == 'play' else print( "Opponent", play_order[data['player']], "passed!") game.playTile( data['action']['tile'], data['action']['right'] ) if data['action']['ac'] == 'play' else game.playPass( ) send( protesting.checkForDuplicatedTiles( game, current_hand, play_order)) #Pos Validation elif data[ 'type'] == messages.ACTION_REQUEST: #Send ACTION_REPLY, this client played print("I'm playing with current hand:", current_hand) tileToPlay = game.chooseValidTile(current_hand) if tileToPlay == None: cheating_chance = randint(0, 99) if cheating_chance < prob_cheat: #Cheating chance = 20% send(cheating.cheatingWithRandomTile(game)) elif not stock_empty: if False and cheating_chance < prob_cheat: print("Fake Pass like Ronaldinho Gaúcho") send(game.playPass()) else: print("No valid play found, gib tile") print(len(stock) - 1) tile_choice = randint(0, len(stock) - 1) drawn_tile = stock.pop(tile_choice) send( game.playDraw( crypto.get_string(drawn_tile))) drawing = True else: print("Passing...") send(game.playPass()) else: send({ 'type': messages.ACTION_REPLY, 'action': { 'ac': 'play', 'tile': tileToPlay[0], 'right': tileToPlay[1] } }) elif data['type'] == messages.OK: if drawing: #This client requested a piece from stock, once all players validate his request, they will enter draw process new_tile = drawProcess(True, drawn_tile) current_hand.append(new_tile) drawing = False draw_tile = None stock_empty = len(stock) <= 0 #stock_empty = True #for testing purposes elif tileToPlay != None: #This client's play validated, removing tile game.playTile(tileToPlay[0], tileToPlay[1]) current_hand.remove(tileToPlay[0]) elif data[ 'type'] == messages.INITIAL_HAND_REQUEST: #Someone complained about cheating!! send({ 'type': messages.INITIAL_HAND_REPLY, 'initial_hand': index_hand }) elif data[ 'type'] == messages.COMMIT_VALIDATION_REQUEST: #Comparison between initial and final bit commits print( "\n\nGame {}! Proceeding to validate everyone's bit commitments for the game recap.\n" .format( "aborted because there was a suspicion of cheating" if data['cheating'] else "finished successfully")) #Generate bit commitment from the data that originated the initial one finalBitcommits = {} for player, hand in data['initial_hands'].items(): if str(player) == str(pseudonym): continue dk = hashlib.sha256() for t in hand: dk.update(t.to_bytes(1, 'big')) finalBitcommits[player] = dk.hexdigest() #Compare both bit commitments for initPlayer, initCommit in bitcommits.items(): for finalPlayer, finalCommit in finalBitcommits.items( ): if str(initPlayer) == str(pseudonym): continue if str(initPlayer) == str(finalPlayer): print( "Comparing initial bit commitment with data sent from {}..." .format(initPlayer), end=" ") if initCommit != finalCommit: print( "\nCould NOT validate {}'s bit commitment! Player sent wrong data" .format(initPlayer)) #Punish player else: print("Validated!".format(initPlayer)) send({'type': messages.OK}) elif data['type'] == messages.POINTS_VALIDATION_REQUEST: print() clientPoints = countPoints(data['final_hands'], data['cheaters'], data['penalty']) for player in clientPoints.keys(): print("Comparing server's score for {}...".format( player), end=" ") if data['points'][player] != clientPoints[player]: print("\nCould NOT validate {}'s points!".format( initPlayer)) else: print("Validated!".format(initPlayer)) send({'type': messages.OK}) elif data['type'] == messages.GAME_END: option = get_end_option(0, data['points']) break except GameEndedException as gee: option = get_end_option(gee.reason, gee.points) if option == 2: claim_points = { 'type': messages.CLAIM_POINTS_REQUEST, 'certificate': cert_pem.hex() } send(claim_points) data = receive() if data['type'] != messages.CLAIM_POINTS_REPLY: raise UnexpectedMessageException() print("\nVerification " + (("confirmed.\nYou are " + data['name'] + " and have a total of " + str(data['points']) + " points.") if data['points'] is not None else "failed.")) print("Closing") # close the connection s.close() return send({"type": messages.OK}) print()