From 12cb66ab2c791444400ca3690dbb4cc7253a6d0f Mon Sep 17 00:00:00 2001 From: Lonami Date: Tue, 30 Aug 2016 17:40:49 +0200 Subject: [PATCH] Reviewed authenticator.py --- network/authenticator.py | 69 ++++++++++++++------------------- parser/tl_generator.py | 4 +- utils/auth_key.py | 9 ++--- utils/helpers.py | 82 +++++++++++++++------------------------- 4 files changed, 66 insertions(+), 98 deletions(-) diff --git a/network/authenticator.py b/network/authenticator.py index d598300c..adadc19f 100644 --- a/network/authenticator.py +++ b/network/authenticator.py @@ -9,7 +9,6 @@ from utils.binary_writer import BinaryWriter from utils.binary_reader import BinaryReader from utils.factorizator import Factorizator from utils.auth_key import AuthKey -from hashlib import sha1 import utils.helpers as utils import time import pyaes @@ -27,8 +26,9 @@ def do_authentication(transport): sender.send(writer.get_bytes()) # Step 1 response: PQ Request + pq, pq_bytes, server_nonce, fingerprints = None, None, None, [] with BinaryReader(sender.receive()) as reader: - response_code = reader.read_int() + response_code = reader.read_int(signed=False) if response_code != 0x05162463: raise AssertionError('Invalid response code: {}'.format(hex(response_code))) @@ -55,15 +55,14 @@ def do_authentication(transport): p, q = Factorizator.factorize(pq) with BinaryWriter() as pq_inner_data_writer: pq_inner_data_writer.write_int(0x83c95aec) # PQ Inner Data - pq_inner_data_writer.tgwrite_bytes(pq_bytes) - # TODO, CHANGE TO_BYTE_ARRAY TO PACK(...); But idk size. And down too. - pq_inner_data_writer.tgwrite_bytes(min(p, q).to_byte_array_unsigned()) - pq_inner_data_writer.tgwrite_bytes(max(p, q).to_byte_array_unsigned()) + pq_inner_data_writer.tgwrite_bytes(utils.get_byte_array(pq, signed=False)) + pq_inner_data_writer.tgwrite_bytes(utils.get_byte_array(min(p, q), signed=False)) + pq_inner_data_writer.tgwrite_bytes(utils.get_byte_array(max(p, q), signed=False)) pq_inner_data_writer.write(nonce) pq_inner_data_writer.write(server_nonce) pq_inner_data_writer.write(new_nonce) - cipher_text = None + cipher_text, target_fingerprint = None, None for fingerprint in fingerprints: cipher_text = rsa.encrypt(str(fingerprint, encoding='utf-8').replace('-', ''), pq_inner_data_writer.get_bytes()) @@ -80,16 +79,18 @@ def do_authentication(transport): req_dh_params_writer.write_int(0xd712e4be) # Req DH Params req_dh_params_writer.write(nonce) req_dh_params_writer.write(server_nonce) - req_dh_params_writer.tgwrite_bytes(min(p, q).to_byte_array_unsigned()) - req_dh_params_writer.tgwrite_bytes(max(p, q).to_byte_array_unsigned()) - req_dh_params_writer.Write(target_fingerprint); + req_dh_params_writer.tgwrite_bytes(utils.get_byte_array(min(p, q), signed=False)) + req_dh_params_writer.tgwrite_bytes(utils.get_byte_array(max(p, q), signed=False)) + req_dh_params_writer.Write(target_fingerprint) req_dh_params_writer.tgwrite_bytes(cipher_text) - req_dh_params_bytes = req_dh_params_writer.get_bytes(); + req_dh_params_bytes = req_dh_params_writer.get_bytes() + sender.send(req_dh_params_bytes) # Step 2 response: DH Exchange + encrypted_answer = None with BinaryReader(sender.receive()) as reader: - response_code = reader.read_int() + response_code = reader.read_int(signed=False) if response_code == 0x79cb045d: raise AssertionError('Server DH params fail: TODO') @@ -98,26 +99,21 @@ def do_authentication(transport): raise AssertionError('Invalid response code: {}'.format(hex(response_code))) nonce_from_server = reader.read(16) - # TODO: - """ if nonce_from_server != nonce: - print('Invalid nonce from server') - return None - """ + raise NotImplementedError('Invalid nonce from server') server_nonce_from_server = reader.read(16) - # TODO: - """ if server_nonce_from_server != server_nonce: - print('Invalid server nonce from server') - return None - """ + raise NotImplementedError('Invalid server nonce from server') + encrypted_answer = reader.tgread_bytes() # Step 3 sending: Complete DH Exchange key, iv = utils.generate_key_data_from_nonces(server_nonce, new_nonce) aes = pyaes.AESModeOfOperationCFB(key, iv, 16) plain_text_answer = aes.decrypt(encrypted_answer) + + g, dh_prime, ga, time_offset = None, None, None, None with BinaryReader(plain_text_answer.encode('ascii')) as dh_inner_data_reader: hashsum = dh_inner_data_reader.read(20) code = dh_inner_data_reader.read_int(signed=False) @@ -133,15 +129,15 @@ def do_authentication(transport): raise AssertionError('Invalid server nonce in encrypted answer') g = dh_inner_data_reader.read_int() - dh_prime = int.from_bytes(dh_inner_data_reader.tgread_bytes(), byteorder='big') - ga = int.from_bytes(dh_inner_data_reader.tgread_bytes(), byteorder='big') + dh_prime = int.from_bytes(dh_inner_data_reader.tgread_bytes(), byteorder='big', signed=True) + ga = int.from_bytes(dh_inner_data_reader.tgread_bytes(), byteorder='big', signed=True) server_time = dh_inner_data_reader.read_int() - time_offset = server_time - int(time.time()) + time_offset = server_time - int(time.time() * 1000) # Multiply by 1000 to get milliseconds b = int.from_bytes(utils.generate_random_bytes(2048), byteorder='big') - gb = pow(g, b, dh_prime) # BigInteger.ValueOf(g).ModPow(b, dhPrime) - gab = pow(ga, b, dh_prime) # ga.ModPow(b, dhPrime) + gb = pow(g, b, dh_prime) + gab = pow(ga, b, dh_prime) # Prepare client DH Inner Data with BinaryWriter() as client_dh_inner_data_writer: @@ -149,10 +145,10 @@ def do_authentication(transport): client_dh_inner_data_writer.write(nonce) client_dh_inner_data_writer.write(server_nonce) client_dh_inner_data_writer.write_long(0) # TODO retry_id - client_dh_inner_data_writer.tgwrite_bytes(gb.to_byte_array_unsigned()) + client_dh_inner_data_writer.tgwrite_bytes(utils.get_byte_array(gb, signed=False)) with BinaryWriter() as client_dh_inner_data_with_hash_writer: - client_dh_inner_data_with_hash_writer.write(sha1(client_dh_inner_data_writer.get_bytes())) + client_dh_inner_data_with_hash_writer.write(utils.sha1(client_dh_inner_data_writer.get_bytes())) client_dh_inner_data_with_hash_writer.write(client_dh_inner_data_writer.get_bytes()) client_dh_inner_data_bytes = client_dh_inner_data_with_hash_writer.get_bytes() @@ -172,22 +168,15 @@ def do_authentication(transport): # Step 3 response: Complete DH Exchange with BinaryReader(sender.receive()) as reader: code = reader.read_int(signed=False) - if code == 0x3bcbf734: + if code == 0x3bcbf734: # DH Gen OK nonce_from_server = reader.read(16) - # TODO: - """ if nonce_from_server != nonce: - print('Invalid nonce from server') - return None - """ + raise NotImplementedError('Invalid nonce from server') server_nonce_from_server = reader.read(16) - # TODO: - """ if server_nonce_from_server != server_nonce: - print('Invalid server nonce from server') - return None - """ + raise NotImplementedError('Invalid server nonce from server') + new_nonce_hash1 = reader.read(16) auth_key = AuthKey(gab) diff --git a/parser/tl_generator.py b/parser/tl_generator.py index 529b6a4e..eee55cd9 100644 --- a/parser/tl_generator.py +++ b/parser/tl_generator.py @@ -297,8 +297,8 @@ def write_onresponse_code(builder, arg, args, name=None): if arg.is_vector: builder.writeln("reader.read_int() # Vector's constructor ID") builder.writeln('{} = [] # Initialize an empty list'.format(name)) - builder.writeln('{}_len = reader.read_int()'.format(name)) - builder.writeln('for _ in range({}_len):'.format(name)) + builder.writeln('{}_len = reader.read_int()'.format(arg.name)) + builder.writeln('for _ in range({}_len):'.format(arg.name)) # Temporary disable .is_vector, not to enter this if again arg.is_vector = False write_onresponse_code(builder, arg, args, name='{}_item'.format(arg.name)) diff --git a/utils/auth_key.py b/utils/auth_key.py index 88b1dcbb..836913a3 100644 --- a/utils/auth_key.py +++ b/utils/auth_key.py @@ -1,6 +1,6 @@ # This file is based on TLSharp # https://github.com/sochix/TLSharp/blob/master/TLSharp.Core/MTProto/Crypto/AuthKey.cs -from hashlib import sha1 +import utils.helpers as utils from utils.binary_writer import BinaryWriter from utils.binary_reader import BinaryReader @@ -8,23 +8,22 @@ from utils.binary_reader import BinaryReader class AuthKey: def __init__(self, gab=None, data=None): if gab: - self.key = gab.to_byte_array_unsigned() + self.key = utils.get_byte_array(gab, signed=False) elif data: self.key = data else: raise AssertionError('Either a gab integer or data bytes array must be provided') - with BinaryReader(sha1(self.key)) as reader: + with BinaryReader(utils.sha1(self.key)) as reader: self.aux_hash = reader.read_long(signed=False) reader.read(4) self.key_id = reader.read_long(signed=False) - def calc_new_nonce_hash(self, new_nonce, number): with BinaryWriter() as writer: writer.write(new_nonce) writer.write_byte(number) writer.write_long(self.aux_hash, signed=False) - new_nonce_hash = sha1(writer.get_bytes())[4:20] + new_nonce_hash = utils.sha1(writer.get_bytes())[4:20] return new_nonce_hash diff --git a/utils/helpers.py b/utils/helpers.py index d5a63c2b..4e3e0ce3 100644 --- a/utils/helpers.py +++ b/utils/helpers.py @@ -1,11 +1,14 @@ import os from utils.binary_writer import BinaryWriter -from hashlib import sha1 +import hashlib + + +bits_per_byte = 8 def generate_random_long(signed=True): """Generates a random long integer (8 bytes), which is optionally signed""" - return int.from_bytes(os.urandom(8), signed=signed) + return int.from_bytes(os.urandom(8), signed=signed, byteorder='big') def generate_random_bytes(count): @@ -13,27 +16,20 @@ def generate_random_bytes(count): return os.urandom(count) +def get_byte_array(integer, signed): + bits = integer.bit_length() + byte_length = (bits + bits_per_byte - 1) // bits_per_byte + return int.to_bytes(integer, length=byte_length, byteorder='big', signed=signed) + + def calc_key(shared_key, msg_key, client): """Calculate the key based on Telegram guidelines, specifying whether it's the client or not""" x = 0 if client else 8 - buffer = [0] * 48 - buffer[0:16] = msg_key - buffer[16:48] = shared_key[x:x + 32] - sha1a = sha1(buffer) - - buffer[0:16] = shared_key[x + 32:x + 48] - buffer[16:32] = msg_key - buffer[32:48] = shared_key[x + 48:x + 64] - sha1b = sha1(buffer) - - buffer[0:32] = shared_key[x + 64:x + 96] - buffer[32:48] = msg_key - sha1c = sha1(buffer) - - buffer[0:16] = msg_key - buffer[16:48] = shared_key[x + 96:x + 128] - sha1d = sha1(buffer) + sha1a = sha1(msg_key + shared_key[x:x + 32]) + sha1b = sha1(shared_key[x + 32:x + 48] + msg_key + shared_key[x + 48:x + 64]) + sha1c = sha1(shared_key[x + 64:x + 96] + msg_key) + sha1d = sha1(msg_key + shared_key[x + 96:x + 128]) key = sha1a[0:8] + sha1b[8:20] + sha1c[4:16] iv = sha1a[8:20] + sha1b[0:8] + sha1c[16:20] + sha1d[0:8] @@ -48,43 +44,27 @@ def calc_msg_key(data): def calc_msg_key_offset(data, offset, limit): """Calculates the message key from offset given data, with an optional offset and limit""" - # TODO untested, may not be offset like this - # In the original code it was as parameters for the sha function, not slicing the array return sha1(data[offset:offset + limit])[4:20] -def generate_key_data_from_nonces(serverNonce, newNonce): - # TODO unsure that this works - nonces = [0] * 48 +def generate_key_data_from_nonces(server_nonce, new_nonce): + hash1 = sha1(bytes(new_nonce + server_nonce)) + hash2 = sha1(bytes(server_nonce + new_nonce)) + hash3 = sha1(bytes(new_nonce + new_nonce)) - nonces[00:32] = newNonce - nonces[32:48] = serverNonce - hash1 = hash(bytes(nonces)) + with BinaryWriter() as key_buffer: + with BinaryWriter() as iv_buffer: + key_buffer.write(hash1) + key_buffer.write(hash2[:12]) - nonces[00:16] = serverNonce - nonces[16:32] = newNonce - hash2 = hash(bytes(nonces)) + iv_buffer.write(hash2[12:20]) + iv_buffer.write(hash3) + iv_buffer.write_byte(new_nonce[:4]) - nonces = [0] * 64 - nonces[00:32] = newNonce - nonces[32:64] = newNonce - hash2 = hash(bytes(nonces)) + return key_buffer.get_bytes(), iv_buffer.get_bytes() - with BinaryWriter() as keyBuffer: - with BinaryWriter() as ivBuffer: - """ - using (var keyBuffer = new MemoryStream(32)) - using (var ivBuffer = new MemoryStream(32)) - { - keyBuffer.Write(hash1, 0, hash1.Length); - keyBuffer.Write(hash2, 0, 12); - ivBuffer.Write(hash2, 12, 8); - ivBuffer.Write(hash3, 0, hash3.Length); - ivBuffer.Write(newNonce, 0, 4); - - return new AESKeyData(keyBuffer.ToArray(), ivBuffer.ToArray()); - } - """ - # TODO implement - raise NotImplementedError() +def sha1(data): + sha = hashlib.sha1 + sha.update(data) + return sha.digest()