2020-03-21 14:43:32 +00:00
|
|
|
# Pyrogram - Telegram MTProto API Client Library for Python
|
2022-01-07 09:23:45 +00:00
|
|
|
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
|
2017-12-05 11:41:07 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# This file is part of Pyrogram.
|
2017-12-05 11:41:07 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# Pyrogram is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Lesser General Public License as published
|
|
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
2017-12-05 11:41:07 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# Pyrogram is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU Lesser General Public License for more details.
|
2017-12-05 11:41:07 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# You should have received a copy of the GNU Lesser General Public License
|
|
|
|
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
import asyncio
|
2017-12-05 11:41:07 +00:00
|
|
|
import logging
|
|
|
|
import time
|
|
|
|
from hashlib import sha1
|
|
|
|
from io import BytesIO
|
|
|
|
from os import urandom
|
|
|
|
|
2019-06-19 14:01:23 +00:00
|
|
|
import pyrogram
|
2020-08-22 06:05:05 +00:00
|
|
|
from pyrogram import raw
|
2017-12-05 11:41:07 +00:00
|
|
|
from pyrogram.connection import Connection
|
2020-08-22 06:05:05 +00:00
|
|
|
from pyrogram.crypto import aes, rsa, prime
|
2021-12-16 20:38:24 +00:00
|
|
|
from pyrogram.errors import SecurityCheckMismatch
|
2020-08-22 06:05:05 +00:00
|
|
|
from pyrogram.raw.core import TLObject, Long, Int
|
2018-06-13 11:37:12 +00:00
|
|
|
from .internals import MsgId
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2019-09-08 17:24:06 +00:00
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
2017-12-05 11:41:07 +00:00
|
|
|
|
|
|
|
class Auth:
|
2017-12-31 10:46:42 +00:00
|
|
|
MAX_RETRIES = 5
|
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
def __init__(self, client: "pyrogram.Client", dc_id: int, test_mode: bool):
|
2017-12-05 11:41:07 +00:00
|
|
|
self.dc_id = dc_id
|
2020-08-22 06:05:05 +00:00
|
|
|
self.test_mode = test_mode
|
2019-06-19 14:01:23 +00:00
|
|
|
self.ipv6 = client.ipv6
|
|
|
|
self.proxy = client.proxy
|
2022-01-11 14:35:38 +00:00
|
|
|
self.mode = client.mode
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2018-05-24 19:19:57 +00:00
|
|
|
self.connection = None
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2018-02-18 16:31:00 +00:00
|
|
|
@staticmethod
|
2019-06-03 12:19:50 +00:00
|
|
|
def pack(data: TLObject) -> bytes:
|
2017-12-05 11:41:07 +00:00
|
|
|
return (
|
2019-03-16 18:23:23 +00:00
|
|
|
bytes(8)
|
|
|
|
+ Long(MsgId())
|
|
|
|
+ Int(len(data.write()))
|
|
|
|
+ data.write()
|
2017-12-05 11:41:07 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def unpack(b: BytesIO):
|
|
|
|
b.seek(20) # Skip auth_key_id (8), message_id (8) and message_length (4)
|
2019-06-03 12:19:50 +00:00
|
|
|
return TLObject.read(b)
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
async def send(self, data: TLObject):
|
2017-12-05 11:41:07 +00:00
|
|
|
data = self.pack(data)
|
2020-08-21 05:28:27 +00:00
|
|
|
await self.connection.send(data)
|
|
|
|
response = BytesIO(await self.connection.recv())
|
2017-12-05 11:41:07 +00:00
|
|
|
|
|
|
|
return self.unpack(response)
|
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
async def create(self):
|
2017-12-05 11:41:07 +00:00
|
|
|
"""
|
|
|
|
https://core.telegram.org/mtproto/auth_key
|
|
|
|
https://core.telegram.org/mtproto/samples-auth_key
|
|
|
|
"""
|
2017-12-31 10:46:42 +00:00
|
|
|
retries_left = self.MAX_RETRIES
|
2017-12-05 11:41:07 +00:00
|
|
|
|
2017-12-09 14:26:33 +00:00
|
|
|
# The server may close the connection at any time, causing the auth key creation to fail.
|
2017-12-31 10:46:42 +00:00
|
|
|
# If that happens, just try again up to MAX_RETRIES times.
|
2017-12-09 14:26:33 +00:00
|
|
|
while True:
|
2022-01-11 14:35:38 +00:00
|
|
|
self.connection = Connection(self.dc_id, self.test_mode, self.ipv6, self.proxy, False, self.mode)
|
2018-05-24 19:19:57 +00:00
|
|
|
|
2017-12-09 14:26:33 +00:00
|
|
|
try:
|
2020-08-22 06:05:05 +00:00
|
|
|
log.info(f"Start creating a new auth key on DC{self.dc_id}")
|
2017-12-09 14:26:33 +00:00
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
await self.connection.connect()
|
2017-12-09 14:26:33 +00:00
|
|
|
|
|
|
|
# Step 1; Step 2
|
|
|
|
nonce = int.from_bytes(urandom(16), "little", signed=True)
|
2020-08-22 06:05:05 +00:00
|
|
|
log.debug(f"Send req_pq: {nonce}")
|
|
|
|
res_pq = await self.send(raw.functions.ReqPqMulti(nonce=nonce))
|
|
|
|
log.debug(f"Got ResPq: {res_pq.server_nonce}")
|
|
|
|
log.debug(f"Server public key fingerprints: {res_pq.server_public_key_fingerprints}")
|
2018-03-08 09:14:26 +00:00
|
|
|
|
|
|
|
for i in res_pq.server_public_key_fingerprints:
|
2020-08-22 06:05:05 +00:00
|
|
|
if i in rsa.server_public_keys:
|
|
|
|
log.debug(f"Using fingerprint: {i}")
|
2018-03-08 09:14:26 +00:00
|
|
|
public_key_fingerprint = i
|
|
|
|
break
|
|
|
|
else:
|
2020-08-22 06:05:05 +00:00
|
|
|
log.debug(f"Fingerprint unknown: {i}")
|
2018-03-08 09:14:26 +00:00
|
|
|
else:
|
|
|
|
raise Exception("Public key not found")
|
2017-12-09 14:26:33 +00:00
|
|
|
|
|
|
|
# Step 3
|
|
|
|
pq = int.from_bytes(res_pq.pq, "big")
|
2020-08-22 06:05:05 +00:00
|
|
|
log.debug(f"Start PQ factorization: {pq}")
|
2017-12-09 14:26:33 +00:00
|
|
|
start = time.time()
|
2020-08-22 06:05:05 +00:00
|
|
|
g = prime.decompose(pq)
|
2017-12-09 14:26:33 +00:00
|
|
|
p, q = sorted((g, pq // g)) # p < q
|
2020-08-22 06:05:05 +00:00
|
|
|
log.debug(f"Done PQ factorization ({round(time.time() - start, 3)}s): {p} {q}")
|
2017-12-09 14:26:33 +00:00
|
|
|
|
|
|
|
# Step 4
|
|
|
|
server_nonce = res_pq.server_nonce
|
|
|
|
new_nonce = int.from_bytes(urandom(32), "little", signed=True)
|
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
data = raw.types.PQInnerData(
|
2019-03-16 15:50:40 +00:00
|
|
|
pq=res_pq.pq,
|
|
|
|
p=p.to_bytes(4, "big"),
|
|
|
|
q=q.to_bytes(4, "big"),
|
|
|
|
nonce=nonce,
|
|
|
|
server_nonce=server_nonce,
|
|
|
|
new_nonce=new_nonce,
|
2017-12-09 14:26:33 +00:00
|
|
|
).write()
|
|
|
|
|
|
|
|
sha = sha1(data).digest()
|
|
|
|
padding = urandom(- (len(data) + len(sha)) % 255)
|
|
|
|
data_with_hash = sha + data + padding
|
2020-08-22 06:05:05 +00:00
|
|
|
encrypted_data = rsa.encrypt(data_with_hash, public_key_fingerprint)
|
2017-12-09 14:26:33 +00:00
|
|
|
|
2019-09-08 17:24:06 +00:00
|
|
|
log.debug("Done encrypt data with RSA")
|
2017-12-09 14:26:33 +00:00
|
|
|
|
|
|
|
# Step 5. TODO: Handle "server_DH_params_fail". Code assumes response is ok
|
2019-09-08 17:24:06 +00:00
|
|
|
log.debug("Send req_DH_params")
|
2020-08-21 05:28:27 +00:00
|
|
|
server_dh_params = await self.send(
|
2020-08-22 06:05:05 +00:00
|
|
|
raw.functions.ReqDHParams(
|
2019-03-16 15:50:40 +00:00
|
|
|
nonce=nonce,
|
|
|
|
server_nonce=server_nonce,
|
|
|
|
p=p.to_bytes(4, "big"),
|
|
|
|
q=q.to_bytes(4, "big"),
|
|
|
|
public_key_fingerprint=public_key_fingerprint,
|
|
|
|
encrypted_data=encrypted_data
|
2017-12-09 14:26:33 +00:00
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
encrypted_answer = server_dh_params.encrypted_answer
|
|
|
|
|
2018-08-31 23:27:22 +00:00
|
|
|
server_nonce = server_nonce.to_bytes(16, "little", signed=True)
|
|
|
|
new_nonce = new_nonce.to_bytes(32, "little", signed=True)
|
2017-12-09 14:26:33 +00:00
|
|
|
|
|
|
|
tmp_aes_key = (
|
2019-03-16 18:23:23 +00:00
|
|
|
sha1(new_nonce + server_nonce).digest()
|
|
|
|
+ sha1(server_nonce + new_nonce).digest()[:12]
|
2017-12-09 14:26:33 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
tmp_aes_iv = (
|
2019-03-16 18:23:23 +00:00
|
|
|
sha1(server_nonce + new_nonce).digest()[12:]
|
|
|
|
+ sha1(new_nonce + new_nonce).digest() + new_nonce[:4]
|
2017-12-09 14:26:33 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
server_nonce = int.from_bytes(server_nonce, "little", signed=True)
|
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
answer_with_hash = aes.ige256_decrypt(encrypted_answer, tmp_aes_key, tmp_aes_iv)
|
2017-12-09 14:26:33 +00:00
|
|
|
answer = answer_with_hash[20:]
|
|
|
|
|
2019-06-03 12:19:50 +00:00
|
|
|
server_dh_inner_data = TLObject.read(BytesIO(answer))
|
2017-12-09 14:26:33 +00:00
|
|
|
|
2019-09-08 17:24:06 +00:00
|
|
|
log.debug("Done decrypting answer")
|
2017-12-09 14:26:33 +00:00
|
|
|
|
|
|
|
dh_prime = int.from_bytes(server_dh_inner_data.dh_prime, "big")
|
|
|
|
delta_time = server_dh_inner_data.server_time - time.time()
|
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
log.debug(f"Delta time: {round(delta_time, 3)}")
|
2017-12-09 14:26:33 +00:00
|
|
|
|
|
|
|
# Step 6
|
|
|
|
g = server_dh_inner_data.g
|
|
|
|
b = int.from_bytes(urandom(256), "big")
|
2018-08-31 23:27:22 +00:00
|
|
|
g_b = pow(g, b, dh_prime).to_bytes(256, "big")
|
2017-12-09 14:26:33 +00:00
|
|
|
|
|
|
|
retry_id = 0
|
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
data = raw.types.ClientDHInnerData(
|
2019-03-16 15:50:40 +00:00
|
|
|
nonce=nonce,
|
|
|
|
server_nonce=server_nonce,
|
|
|
|
retry_id=retry_id,
|
|
|
|
g_b=g_b
|
2017-12-09 14:26:33 +00:00
|
|
|
).write()
|
|
|
|
|
|
|
|
sha = sha1(data).digest()
|
|
|
|
padding = urandom(- (len(data) + len(sha)) % 16)
|
|
|
|
data_with_hash = sha + data + padding
|
2020-08-22 06:05:05 +00:00
|
|
|
encrypted_data = aes.ige256_encrypt(data_with_hash, tmp_aes_key, tmp_aes_iv)
|
2017-12-09 14:26:33 +00:00
|
|
|
|
2019-09-08 17:24:06 +00:00
|
|
|
log.debug("Send set_client_DH_params")
|
2020-08-21 05:28:27 +00:00
|
|
|
set_client_dh_params_answer = await self.send(
|
2020-08-22 06:05:05 +00:00
|
|
|
raw.functions.SetClientDHParams(
|
2019-03-16 15:50:40 +00:00
|
|
|
nonce=nonce,
|
|
|
|
server_nonce=server_nonce,
|
|
|
|
encrypted_data=encrypted_data
|
2017-12-09 14:26:33 +00:00
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
# TODO: Handle "auth_key_aux_hash" if the previous step fails
|
|
|
|
|
|
|
|
# Step 7; Step 8
|
|
|
|
g_a = int.from_bytes(server_dh_inner_data.g_a, "big")
|
2018-08-31 23:27:22 +00:00
|
|
|
auth_key = pow(g_a, b, dh_prime).to_bytes(256, "big")
|
|
|
|
server_nonce = server_nonce.to_bytes(16, "little", signed=True)
|
2017-12-09 14:26:33 +00:00
|
|
|
|
|
|
|
# TODO: Handle errors
|
|
|
|
|
|
|
|
#######################
|
|
|
|
# Security checks
|
|
|
|
#######################
|
|
|
|
|
2021-12-16 20:38:24 +00:00
|
|
|
SecurityCheckMismatch.check(dh_prime == prime.CURRENT_DH_PRIME)
|
2019-09-08 17:24:06 +00:00
|
|
|
log.debug("DH parameters check: OK")
|
2017-12-09 14:26:33 +00:00
|
|
|
|
|
|
|
# https://core.telegram.org/mtproto/security_guidelines#g-a-and-g-b-validation
|
|
|
|
g_b = int.from_bytes(g_b, "big")
|
2021-12-16 20:38:24 +00:00
|
|
|
SecurityCheckMismatch.check(1 < g < dh_prime - 1)
|
|
|
|
SecurityCheckMismatch.check(1 < g_a < dh_prime - 1)
|
|
|
|
SecurityCheckMismatch.check(1 < g_b < dh_prime - 1)
|
|
|
|
SecurityCheckMismatch.check(2 ** (2048 - 64) < g_a < dh_prime - 2 ** (2048 - 64))
|
|
|
|
SecurityCheckMismatch.check(2 ** (2048 - 64) < g_b < dh_prime - 2 ** (2048 - 64))
|
2019-09-08 17:24:06 +00:00
|
|
|
log.debug("g_a and g_b validation: OK")
|
2017-12-09 14:26:33 +00:00
|
|
|
|
|
|
|
# https://core.telegram.org/mtproto/security_guidelines#checking-sha1-hash-values
|
|
|
|
answer = server_dh_inner_data.write() # Call .write() to remove padding
|
2021-12-16 20:38:24 +00:00
|
|
|
SecurityCheckMismatch.check(answer_with_hash[:20] == sha1(answer).digest())
|
2019-09-08 17:24:06 +00:00
|
|
|
log.debug("SHA1 hash values check: OK")
|
2017-12-09 14:26:33 +00:00
|
|
|
|
|
|
|
# https://core.telegram.org/mtproto/security_guidelines#checking-nonce-server-nonce-and-new-nonce-fields
|
|
|
|
# 1st message
|
2021-12-16 20:38:24 +00:00
|
|
|
SecurityCheckMismatch.check(nonce == res_pq.nonce)
|
2017-12-09 14:26:33 +00:00
|
|
|
# 2nd message
|
|
|
|
server_nonce = int.from_bytes(server_nonce, "little", signed=True)
|
2021-12-16 20:38:24 +00:00
|
|
|
SecurityCheckMismatch.check(nonce == server_dh_params.nonce)
|
|
|
|
SecurityCheckMismatch.check(server_nonce == server_dh_params.server_nonce)
|
2017-12-09 14:26:33 +00:00
|
|
|
# 3rd message
|
2021-12-16 20:38:24 +00:00
|
|
|
SecurityCheckMismatch.check(nonce == set_client_dh_params_answer.nonce)
|
|
|
|
SecurityCheckMismatch.check(server_nonce == set_client_dh_params_answer.server_nonce)
|
2018-08-31 23:27:22 +00:00
|
|
|
server_nonce = server_nonce.to_bytes(16, "little", signed=True)
|
2019-09-08 17:24:06 +00:00
|
|
|
log.debug("Nonce fields check: OK")
|
2017-12-09 14:26:33 +00:00
|
|
|
|
|
|
|
# Step 9
|
2020-08-22 06:05:05 +00:00
|
|
|
server_salt = aes.xor(new_nonce[:8], server_nonce[:8])
|
2017-12-09 14:26:33 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
log.debug(f"Server salt: {int.from_bytes(server_salt, 'little')}")
|
2017-12-09 14:26:33 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
log.info(f"Done auth key exchange: {set_client_dh_params_answer.__class__.__name__}")
|
2017-12-23 13:02:14 +00:00
|
|
|
except Exception as e:
|
2017-12-31 10:46:42 +00:00
|
|
|
if retries_left:
|
|
|
|
retries_left -= 1
|
|
|
|
else:
|
|
|
|
raise e
|
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
await asyncio.sleep(1)
|
2017-12-09 14:26:33 +00:00
|
|
|
continue
|
|
|
|
else:
|
|
|
|
return auth_key
|
|
|
|
finally:
|
|
|
|
self.connection.close()
|