-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathauth.py
More file actions
281 lines (230 loc) · 11.2 KB
/
auth.py
File metadata and controls
281 lines (230 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# 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.
#
# 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.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
import asyncio
import logging
import time
from hashlib import sha1
from io import BytesIO
from os import urandom
import pyrogram
from pyrogram import raw
from pyrogram.connection import Connection
from pyrogram.crypto import aes, rsa, prime
from pyrogram.errors import SecurityCheckMismatch
from pyrogram.raw.core import TLObject, Long, Int
from .internals import MsgId
log = logging.getLogger(__name__)
class Auth:
MAX_RETRIES = 5
def __init__(self, client: "pyrogram.Client", dc_id: int, test_mode: bool):
self.dc_id = dc_id
self.test_mode = test_mode
self.ipv6 = client.ipv6
self.proxy = client.proxy
self.connection = None
@staticmethod
def pack(data: TLObject) -> bytes:
return (
bytes(8)
+ Long(MsgId())
+ Int(len(data.write()))
+ data.write()
)
@staticmethod
def unpack(b: BytesIO):
b.seek(20) # Skip auth_key_id (8), message_id (8) and message_length (4)
return TLObject.read(b)
async def invoke(self, data: TLObject):
data = self.pack(data)
await self.connection.send(data)
response = BytesIO(await self.connection.recv())
return self.unpack(response)
async def create(self):
"""
https://core.telegram.org/mtproto/auth_key
https://core.telegram.org/mtproto/samples-auth_key
"""
retries_left = self.MAX_RETRIES
# The server may close the connection at any time, causing the auth key creation to fail.
# If that happens, just try again up to MAX_RETRIES times.
while True:
self.connection = Connection(self.dc_id, self.test_mode, self.ipv6, self.proxy)
try:
log.info("Start creating a new auth key on DC%s", self.dc_id)
await self.connection.connect()
# Step 1; Step 2
nonce = int.from_bytes(urandom(16), "little", signed=True)
log.debug("Send req_pq: %s", nonce)
res_pq = await self.invoke(raw.functions.ReqPqMulti(nonce=nonce))
log.debug("Got ResPq: %s", res_pq.server_nonce)
log.debug("Server public key fingerprints: %s", res_pq.server_public_key_fingerprints)
for i in res_pq.server_public_key_fingerprints:
if i in rsa.server_public_keys:
log.debug("Using fingerprint: %s", i)
public_key_fingerprint = i
break
else:
log.debug("Fingerprint unknown: %s", i)
else:
raise Exception("Public key not found")
# Step 3
pq = int.from_bytes(res_pq.pq, "big")
log.debug("Start PQ factorization: %s", pq)
start = time.time()
g = prime.decompose(pq)
p, q = sorted((g, pq // g)) # p < q
log.debug("Done PQ factorization (%ss): %s %s", round(time.time() - start, 3), p, q)
# Step 4
server_nonce = res_pq.server_nonce
new_nonce = int.from_bytes(urandom(32), "little", signed=True)
data = raw.types.PQInnerData(
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,
).write()
sha = sha1(data).digest()
padding = urandom(- (len(data) + len(sha)) % 255)
data_with_hash = sha + data + padding
encrypted_data = rsa.encrypt(data_with_hash, public_key_fingerprint)
log.debug("Done encrypt data with RSA")
# Step 5. TODO: Handle "server_DH_params_fail". Code assumes response is ok
log.debug("Send req_DH_params")
server_dh_params = await self.invoke(
raw.functions.ReqDHParams(
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
)
)
encrypted_answer = server_dh_params.encrypted_answer
server_nonce = server_nonce.to_bytes(16, "little", signed=True)
new_nonce = new_nonce.to_bytes(32, "little", signed=True)
tmp_aes_key = (
sha1(new_nonce + server_nonce).digest()
+ sha1(server_nonce + new_nonce).digest()[:12]
)
tmp_aes_iv = (
sha1(server_nonce + new_nonce).digest()[12:]
+ sha1(new_nonce + new_nonce).digest() + new_nonce[:4]
)
server_nonce = int.from_bytes(server_nonce, "little", signed=True)
answer_with_hash = aes.ige256_decrypt(encrypted_answer, tmp_aes_key, tmp_aes_iv)
answer = answer_with_hash[20:]
server_dh_inner_data = TLObject.read(BytesIO(answer))
log.debug("Done decrypting answer")
dh_prime = int.from_bytes(server_dh_inner_data.dh_prime, "big")
delta_time = server_dh_inner_data.server_time - time.time()
log.debug("Delta time: %s", round(delta_time, 3))
# Step 6
g = server_dh_inner_data.g
b = int.from_bytes(urandom(256), "big")
g_b = pow(g, b, dh_prime).to_bytes(256, "big")
retry_id = 0
data = raw.types.ClientDHInnerData(
nonce=nonce,
server_nonce=server_nonce,
retry_id=retry_id,
g_b=g_b
).write()
sha = sha1(data).digest()
padding = urandom(- (len(data) + len(sha)) % 16)
data_with_hash = sha + data + padding
encrypted_data = aes.ige256_encrypt(data_with_hash, tmp_aes_key, tmp_aes_iv)
log.debug("Send set_client_DH_params")
set_client_dh_params_answer = await self.invoke(
raw.functions.SetClientDHParams(
nonce=nonce,
server_nonce=server_nonce,
encrypted_data=encrypted_data
)
)
# 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")
auth_key = pow(g_a, b, dh_prime).to_bytes(256, "big")
server_nonce = server_nonce.to_bytes(16, "little", signed=True)
# TODO: Handle errors
#######################
# Security checks
#######################
SecurityCheckMismatch.check(dh_prime == prime.CURRENT_DH_PRIME, "dh_prime == prime.CURRENT_DH_PRIME")
log.debug("DH parameters check: OK")
# https://core.telegram.org/mtproto/security_guidelines#g-a-and-g-b-validation
g_b = int.from_bytes(g_b, "big")
SecurityCheckMismatch.check(1 < g < dh_prime - 1, "1 < g < dh_prime - 1")
SecurityCheckMismatch.check(1 < g_a < dh_prime - 1, "1 < g_a < dh_prime - 1")
SecurityCheckMismatch.check(1 < g_b < dh_prime - 1, "1 < g_b < dh_prime - 1")
SecurityCheckMismatch.check(
2 ** (2048 - 64) < g_a < dh_prime - 2 ** (2048 - 64),
"2 ** (2048 - 64) < g_a < dh_prime - 2 ** (2048 - 64)"
)
SecurityCheckMismatch.check(
2 ** (2048 - 64) < g_b < dh_prime - 2 ** (2048 - 64),
"2 ** (2048 - 64) < g_b < dh_prime - 2 ** (2048 - 64)"
)
log.debug("g_a and g_b validation: OK")
# https://core.telegram.org/mtproto/security_guidelines#checking-sha1-hash-values
answer = server_dh_inner_data.write() # Call .write() to remove padding
SecurityCheckMismatch.check(
answer_with_hash[:20] == sha1(answer).digest(),
"answer_with_hash[:20] == sha1(answer).digest()"
)
log.debug("SHA1 hash values check: OK")
# https://core.telegram.org/mtproto/security_guidelines#checking-nonce-server-nonce-and-new-nonce-fields
# 1st message
SecurityCheckMismatch.check(nonce == res_pq.nonce, "nonce == res_pq.nonce")
# 2nd message
server_nonce = int.from_bytes(server_nonce, "little", signed=True)
SecurityCheckMismatch.check(nonce == server_dh_params.nonce, "nonce == server_dh_params.nonce")
SecurityCheckMismatch.check(
server_nonce == server_dh_params.server_nonce,
"server_nonce == server_dh_params.server_nonce"
)
# 3rd message
SecurityCheckMismatch.check(
nonce == set_client_dh_params_answer.nonce,
"nonce == set_client_dh_params_answer.nonce"
)
SecurityCheckMismatch.check(
server_nonce == set_client_dh_params_answer.server_nonce,
"server_nonce == set_client_dh_params_answer.server_nonce"
)
server_nonce = server_nonce.to_bytes(16, "little", signed=True)
log.debug("Nonce fields check: OK")
# Step 9
server_salt = aes.xor(new_nonce[:8], server_nonce[:8])
log.debug("Server salt: %s", int.from_bytes(server_salt, "little"))
log.info("Done auth key exchange: %s", set_client_dh_params_answer.__class__.__name__)
except Exception as e:
log.info("Retrying due to %s: %s", type(e).__name__, e)
if retries_left:
retries_left -= 1
else:
raise e
await asyncio.sleep(1)
continue
else:
return auth_key
finally:
await self.connection.close()