Handshake.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. /*
  2. * This is the source code of tgnet library v. 1.1
  3. * It is licensed under GNU GPL v. 2 or later.
  4. * You should have received a copy of the license in this archive (see LICENSE).
  5. *
  6. * Copyright Nikolai Kudashov, 2015-2018.
  7. */
  8. #include <stdlib.h>
  9. #include <algorithm>
  10. #include <memory>
  11. #include <openssl/rand.h>
  12. #include <openssl/sha.h>
  13. #include <openssl/bn.h>
  14. #include <openssl/pem.h>
  15. #include <openssl/aes.h>
  16. #include <memory.h>
  17. #include "Handshake.h"
  18. #include "FileLog.h"
  19. #include "Datacenter.h"
  20. #include "ConnectionsManager.h"
  21. #include "MTProtoScheme.h"
  22. #include "ApiScheme.h"
  23. #include "BuffersStorage.h"
  24. #include "NativeByteBuffer.h"
  25. #include "Config.h"
  26. #include "Connection.h"
  27. thread_local static std::vector<std::string> serverPublicKeys;
  28. thread_local static std::vector<uint64_t> serverPublicKeysFingerprints;
  29. thread_local static std::map<int32_t, std::string> cdnPublicKeys;
  30. thread_local static std::map<int32_t, uint64_t> cdnPublicKeysFingerprints;
  31. thread_local static std::vector<Datacenter *> cdnWaitingDatacenters;
  32. thread_local static bool loadingCdnKeys = false;
  33. thread_local static BN_CTX *bnContext = nullptr;
  34. thread_local static Config *cdnConfig = nullptr;
  35. Handshake::Handshake(Datacenter *datacenter, HandshakeType type, HandshakeDelegate *handshakeDelegate) {
  36. currentDatacenter = datacenter;
  37. handshakeType = type;
  38. delegate = handshakeDelegate;
  39. }
  40. Handshake::~Handshake() {
  41. cleanupHandshake();
  42. }
  43. void Handshake::beginHandshake(bool reconnect) {
  44. if (LOGS_ENABLED) DEBUG_D("account%u dc%u handshake: begin, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  45. cleanupHandshake();
  46. Connection *connection = getConnection();
  47. handshakeState = 1;
  48. if (reconnect) {
  49. connection->suspendConnection();
  50. connection->connect();
  51. }
  52. auto request = new TL_req_pq_multi();
  53. request->nonce = std::make_unique<ByteArray>(16);
  54. RAND_bytes(request->nonce->bytes, 16);
  55. authNonce = new ByteArray(request->nonce.get());
  56. sendRequestData(request, true);
  57. }
  58. void Handshake::cleanupHandshake() {
  59. handshakeState = 0;
  60. if (handshakeRequest != nullptr) {
  61. delete handshakeRequest;
  62. handshakeRequest = nullptr;
  63. }
  64. if (handshakeServerSalt != nullptr) {
  65. delete handshakeServerSalt;
  66. handshakeServerSalt = nullptr;
  67. }
  68. if (authNonce != nullptr) {
  69. delete authNonce;
  70. authNonce = nullptr;
  71. }
  72. if (authServerNonce != nullptr) {
  73. delete authServerNonce;
  74. authServerNonce = nullptr;
  75. }
  76. if (authNewNonce != nullptr) {
  77. delete authNewNonce;
  78. authNewNonce = nullptr;
  79. }
  80. if (handshakeAuthKey != nullptr) {
  81. delete handshakeAuthKey;
  82. handshakeAuthKey = nullptr;
  83. }
  84. if (authKeyTempPending != nullptr) {
  85. delete authKeyTempPending;
  86. authKeyTempPending = nullptr;
  87. }
  88. if (authKeyPendingMessageId != 0 || authKeyPendingRequestId != 0) {
  89. ConnectionsManager::getInstance(currentDatacenter->instanceNum).cancelRequestInternal(authKeyPendingRequestId, authKeyPendingMessageId, false, false);
  90. authKeyPendingMessageId = 0;
  91. authKeyPendingRequestId = 0;
  92. }
  93. authKeyTempPendingId = 0;
  94. }
  95. inline Connection *Handshake::getConnection() {
  96. return handshakeType == HandshakeTypeMediaTemp ? currentDatacenter->createGenericMediaConnection() : currentDatacenter->createGenericConnection();
  97. }
  98. void Handshake::sendRequestData(TLObject *object, bool important) {
  99. uint32_t messageLength = object->getObjectSize();
  100. NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(20 + messageLength);
  101. buffer->writeInt64(0);
  102. buffer->writeInt64(ConnectionsManager::getInstance(currentDatacenter->instanceNum).generateMessageId());
  103. buffer->writeInt32(messageLength);
  104. object->serializeToStream(buffer);
  105. getConnection()->sendData(buffer, false, false);
  106. if (important) {
  107. if (handshakeRequest != object) {
  108. if (handshakeRequest != nullptr) {
  109. delete handshakeRequest;
  110. }
  111. handshakeRequest = object;
  112. }
  113. } else {
  114. delete object;
  115. }
  116. }
  117. inline uint64_t gcd(uint64_t a, uint64_t b) {
  118. while (a != 0 && b != 0) {
  119. while ((b & 1) == 0) {
  120. b >>= 1;
  121. }
  122. while ((a & 1) == 0) {
  123. a >>= 1;
  124. }
  125. if (a > b) {
  126. a -= b;
  127. } else {
  128. b -= a;
  129. }
  130. }
  131. return b == 0 ? a : b;
  132. }
  133. inline bool factorizeValue(uint64_t what, uint32_t &p, uint32_t &q) {
  134. int32_t it = 0, i, j;
  135. uint64_t g = 0;
  136. for (i = 0; i < 3 || it < 1000; i++) {
  137. uint64_t t = ((lrand48() & 15) + 17) % what;
  138. uint64_t x = (long long) lrand48() % (what - 1) + 1, y = x;
  139. int32_t lim = 1 << (i + 18);
  140. for (j = 1; j < lim; j++) {
  141. ++it;
  142. uint64_t a = x, b = x, c = t;
  143. while (b) {
  144. if (b & 1) {
  145. c += a;
  146. if (c >= what) {
  147. c -= what;
  148. }
  149. }
  150. a += a;
  151. if (a >= what) {
  152. a -= what;
  153. }
  154. b >>= 1;
  155. }
  156. x = c;
  157. uint64_t z = x < y ? what + x - y : x - y;
  158. g = gcd(z, what);
  159. if (g != 1) {
  160. break;
  161. }
  162. if (!(j & (j - 1))) {
  163. y = x;
  164. }
  165. }
  166. if (g > 1 && g < what) {
  167. break;
  168. }
  169. }
  170. if (g > 1 && g < what) {
  171. p = (uint32_t) g;
  172. q = (uint32_t) (what / g);
  173. if (p > q) {
  174. uint32_t tmp = p;
  175. p = q;
  176. q = tmp;
  177. }
  178. return true;
  179. } else {
  180. if (LOGS_ENABLED) DEBUG_FATAL("factorization failed for %" PRIu64, what);
  181. p = 0;
  182. q = 0;
  183. return false;
  184. }
  185. }
  186. inline bool check_prime(BIGNUM *p) {
  187. int result = 0;
  188. if (!BN_primality_test(&result, p, 64, bnContext, 0, NULL)) {
  189. if (LOGS_ENABLED) DEBUG_FATAL("OpenSSL error at BN_primality_test");
  190. return false;
  191. }
  192. return result != 0;
  193. }
  194. inline bool isGoodPrime(BIGNUM *p, uint32_t g) {
  195. if (g < 2 || g > 7 || BN_num_bits(p) != 2048) {
  196. return false;
  197. }
  198. BIGNUM *t = BN_new();
  199. BIGNUM *dh_g = BN_new();
  200. if (!BN_set_word(dh_g, 4 * g)) {
  201. if (LOGS_ENABLED) DEBUG_FATAL("OpenSSL error at BN_set_word(dh_g, 4 * g)");
  202. BN_free(t);
  203. BN_free(dh_g);
  204. return false;
  205. }
  206. if (!BN_mod(t, p, dh_g, bnContext)) {
  207. if (LOGS_ENABLED) DEBUG_FATAL("OpenSSL error at BN_mod");
  208. BN_free(t);
  209. BN_free(dh_g);
  210. return false;
  211. }
  212. uint64_t x = BN_get_word(t);
  213. if (x >= 4 * g) {
  214. if (LOGS_ENABLED) DEBUG_FATAL("OpenSSL error at BN_get_word");
  215. BN_free(t);
  216. BN_free(dh_g);
  217. return false;
  218. }
  219. BN_free(dh_g);
  220. bool result = true;
  221. switch (g) {
  222. case 2:
  223. if (x != 7) {
  224. result = false;
  225. }
  226. break;
  227. case 3:
  228. if (x % 3 != 2) {
  229. result = false;
  230. }
  231. break;
  232. case 5:
  233. if (x % 5 != 1 && x % 5 != 4) {
  234. result = false;
  235. }
  236. break;
  237. case 6:
  238. if (x != 19 && x != 23) {
  239. result = false;
  240. }
  241. break;
  242. case 7:
  243. if (x % 7 != 3 && x % 7 != 5 && x % 7 != 6) {
  244. result = false;
  245. }
  246. break;
  247. default:
  248. break;
  249. }
  250. char *prime = BN_bn2hex(p);
  251. static const char *goodPrime = "c71caeb9c6b1c9048e6c522f70f13f73980d40238e3e21c14934d037563d930f48198a0aa7c14058229493d22530f4dbfa336f6e0ac925139543aed44cce7c3720fd51f69458705ac68cd4fe6b6b13abdc9746512969328454f18faf8c595f642477fe96bb2a941d5bcd1d4ac8cc49880708fa9b378e3c4f3a9060bee67cf9a4a4a695811051907e162753b56b0f6b410dba74d8a84b2a14b3144e0ef1284754fd17ed950d5965b4b9dd46582db1178d169c6bc465b0d6ff9ca3928fef5b9ae4e418fc15e83ebea0f87fa9ff5eed70050ded2849f47bf959d956850ce929851f0d8115f635b105ee2e4e15d04b2454bf6f4fadf034b10403119cd8e3b92fcc5b";
  252. if (!strcasecmp(prime, goodPrime)) {
  253. OPENSSL_free(prime);
  254. BN_free(t);
  255. return true;
  256. }
  257. OPENSSL_free(prime);
  258. if (!result || !check_prime(p)) {
  259. BN_free(t);
  260. return false;
  261. }
  262. BIGNUM *b = BN_new();
  263. if (!BN_set_word(b, 2)) {
  264. if (LOGS_ENABLED) DEBUG_E("OpenSSL error at BN_set_word(b, 2)");
  265. BN_free(b);
  266. BN_free(t);
  267. return false;
  268. }
  269. if (!BN_div(t, 0, p, b, bnContext)) {
  270. if (LOGS_ENABLED) DEBUG_E("OpenSSL error at BN_div");
  271. BN_free(b);
  272. BN_free(t);
  273. return false;
  274. }
  275. if (!check_prime(t)) {
  276. result = false;
  277. }
  278. BN_free(b);
  279. BN_free(t);
  280. return result;
  281. }
  282. inline bool isGoodGaAndGb(BIGNUM *g_a, BIGNUM *p) {
  283. if (BN_num_bytes(g_a) > 256 || BN_num_bits(g_a) < 2048 - 64 || BN_cmp(p, g_a) <= 0) {
  284. return false;
  285. }
  286. BIGNUM *dif = BN_new();
  287. BN_sub(dif, p, g_a);
  288. if (BN_num_bits(dif) < 2048 - 64) {
  289. BN_free(dif);
  290. return false;
  291. }
  292. BN_free(dif);
  293. return true;
  294. }
  295. void Handshake::cleanupServerKeys() {
  296. serverPublicKeys.clear();
  297. serverPublicKeysFingerprints.clear();
  298. }
  299. void Handshake::processHandshakeResponse(TLObject *message, int64_t messageId) {
  300. if (handshakeState == 0) {
  301. return;
  302. }
  303. const std::type_info &typeInfo = typeid(*message);
  304. if (typeInfo == typeid(TL_resPQ)) {
  305. if (handshakeState != 1) {
  306. sendAckRequest(messageId);
  307. return;
  308. }
  309. handshakeState = 2;
  310. auto result = (TL_resPQ *) message;
  311. if (authNonce->isEqualTo(result->nonce.get())) {
  312. std::string key = "";
  313. int64_t keyFingerprint = 0;
  314. size_t count1 = result->server_public_key_fingerprints.size();
  315. if (currentDatacenter->isCdnDatacenter) {
  316. auto iter = cdnPublicKeysFingerprints.find(currentDatacenter->datacenterId);
  317. if (iter != cdnPublicKeysFingerprints.end()) {
  318. for (uint32_t a = 0; a < count1; a++) {
  319. if ((uint64_t) result->server_public_key_fingerprints[a] == iter->second) {
  320. keyFingerprint = iter->second;
  321. key = cdnPublicKeys[currentDatacenter->datacenterId];
  322. }
  323. }
  324. }
  325. } else {
  326. if (serverPublicKeys.empty()) {
  327. if (ConnectionsManager::getInstance(currentDatacenter->instanceNum).testBackend) {
  328. serverPublicKeys.emplace_back("-----BEGIN RSA PUBLIC KEY-----\n"
  329. "MIIBCgKCAQEAyMEdY1aR+sCR3ZSJrtztKTKqigvO/vBfqACJLZtS7QMgCGXJ6XIR\n"
  330. "yy7mx66W0/sOFa7/1mAZtEoIokDP3ShoqF4fVNb6XeqgQfaUHd8wJpDWHcR2OFwv\n"
  331. "plUUI1PLTktZ9uW2WE23b+ixNwJjJGwBDJPQEQFBE+vfmH0JP503wr5INS1poWg/\n"
  332. "j25sIWeYPHYeOrFp/eXaqhISP6G+q2IeTaWTXpwZj4LzXq5YOpk4bYEQ6mvRq7D1\n"
  333. "aHWfYmlEGepfaYR8Q0YqvvhYtMte3ITnuSJs171+GDqpdKcSwHnd6FudwGO4pcCO\n"
  334. "j4WcDuXc2CTHgH8gFTNhp/Y8/SpDOhvn9QIDAQAB\n"
  335. "-----END RSA PUBLIC KEY-----");
  336. serverPublicKeysFingerprints.push_back(0xb25898df208d2603);
  337. } else {
  338. serverPublicKeys.emplace_back("-----BEGIN RSA PUBLIC KEY-----\n"
  339. "MIIBCgKCAQEA6LszBcC1LGzyr992NzE0ieY+BSaOW622Aa9Bd4ZHLl+TuFQ4lo4g\n"
  340. "5nKaMBwK/BIb9xUfg0Q29/2mgIR6Zr9krM7HjuIcCzFvDtr+L0GQjae9H0pRB2OO\n"
  341. "62cECs5HKhT5DZ98K33vmWiLowc621dQuwKWSQKjWf50XYFw42h21P2KXUGyp2y/\n"
  342. "+aEyZ+uVgLLQbRA1dEjSDZ2iGRy12Mk5gpYc397aYp438fsJoHIgJ2lgMv5h7WY9\n"
  343. "t6N/byY9Nw9p21Og3AoXSL2q/2IJ1WRUhebgAdGVMlV1fkuOQoEzR7EdpqtQD9Cs\n"
  344. "5+bfo3Nhmcyvk5ftB0WkJ9z6bNZ7yxrP8wIDAQAB\n"
  345. "-----END RSA PUBLIC KEY-----");
  346. serverPublicKeysFingerprints.push_back(0xd09d1d85de64fd85);
  347. }
  348. }
  349. size_t count2 = serverPublicKeysFingerprints.size();
  350. for (uint32_t a = 0; a < count1; a++) {
  351. for (uint32_t b = 0; b < count2; b++) {
  352. if ((uint64_t) result->server_public_key_fingerprints[a] == serverPublicKeysFingerprints[b]) {
  353. keyFingerprint = result->server_public_key_fingerprints[a];
  354. key = serverPublicKeys[b];
  355. break;
  356. }
  357. }
  358. if (keyFingerprint != 0) {
  359. break;
  360. }
  361. }
  362. }
  363. if (keyFingerprint == 0) {
  364. if (currentDatacenter->isCdnDatacenter) {
  365. if (LOGS_ENABLED) DEBUG_D("account%u dc%u handshake: can't find valid cdn server public key, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  366. loadCdnConfig(currentDatacenter);
  367. } else {
  368. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: can't find valid server public key, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  369. beginHandshake(false);
  370. }
  371. return;
  372. }
  373. authServerNonce = new ByteArray(result->server_nonce.get());
  374. uint64_t pq = ((uint64_t) (result->pq->bytes[0] & 0xff) << 56) |
  375. ((uint64_t) (result->pq->bytes[1] & 0xff) << 48) |
  376. ((uint64_t) (result->pq->bytes[2] & 0xff) << 40) |
  377. ((uint64_t) (result->pq->bytes[3] & 0xff) << 32) |
  378. ((uint64_t) (result->pq->bytes[4] & 0xff) << 24) |
  379. ((uint64_t) (result->pq->bytes[5] & 0xff) << 16) |
  380. ((uint64_t) (result->pq->bytes[6] & 0xff) << 8) |
  381. ((uint64_t) (result->pq->bytes[7] & 0xff));
  382. uint32_t p, q;
  383. if (!factorizeValue(pq, p, q)) {
  384. beginHandshake(false);
  385. return;
  386. }
  387. auto request = new TL_req_DH_params();
  388. request->nonce = std::make_unique<ByteArray>(new ByteArray(authNonce));
  389. request->server_nonce = std::make_unique<ByteArray>(new ByteArray(authServerNonce));
  390. request->p = std::make_unique<ByteArray>(new ByteArray(4));
  391. request->p->bytes[3] = (uint8_t) p;
  392. request->p->bytes[2] = (uint8_t) (p >> 8);
  393. request->p->bytes[1] = (uint8_t) (p >> 16);
  394. request->p->bytes[0] = (uint8_t) (p >> 24);
  395. request->q = std::make_unique<ByteArray>(new ByteArray(4));
  396. request->q->bytes[3] = (uint8_t) q;
  397. request->q->bytes[2] = (uint8_t) (q >> 8);
  398. request->q->bytes[1] = (uint8_t) (q >> 16);
  399. request->q->bytes[0] = (uint8_t) (q >> 24);
  400. request->public_key_fingerprint = keyFingerprint;
  401. TLObject *innerData;
  402. if (handshakeType == HandshakeTypePerm) {
  403. auto tl_p_q_inner_data = new TL_p_q_inner_data_dc();
  404. tl_p_q_inner_data->nonce = std::make_unique<ByteArray>(authNonce);
  405. tl_p_q_inner_data->server_nonce = std::make_unique<ByteArray>(authServerNonce);
  406. tl_p_q_inner_data->pq = std::make_unique<ByteArray>(new ByteArray(result->pq.get()));
  407. tl_p_q_inner_data->p = std::make_unique<ByteArray>(new ByteArray(request->p.get()));
  408. tl_p_q_inner_data->q = std::make_unique<ByteArray>(new ByteArray(request->q.get()));
  409. tl_p_q_inner_data->new_nonce = std::make_unique<ByteArray>(new ByteArray(32));
  410. if (ConnectionsManager::getInstance(currentDatacenter->instanceNum).testBackend) {
  411. tl_p_q_inner_data->dc = 10000 + currentDatacenter->datacenterId;
  412. } else {
  413. tl_p_q_inner_data->dc = currentDatacenter->datacenterId;
  414. }
  415. RAND_bytes(tl_p_q_inner_data->new_nonce->bytes, 32);
  416. authNewNonce = new ByteArray(tl_p_q_inner_data->new_nonce.get());
  417. innerData = tl_p_q_inner_data;
  418. } else {
  419. auto tl_p_q_inner_data_temp = new TL_p_q_inner_data_temp_dc();
  420. tl_p_q_inner_data_temp->nonce = std::make_unique<ByteArray>(new ByteArray(authNonce));
  421. tl_p_q_inner_data_temp->server_nonce = std::make_unique<ByteArray>(new ByteArray(authServerNonce));
  422. tl_p_q_inner_data_temp->pq = std::make_unique<ByteArray>(new ByteArray(result->pq.get()));
  423. tl_p_q_inner_data_temp->p = std::make_unique<ByteArray>(new ByteArray(request->p.get()));
  424. tl_p_q_inner_data_temp->q = std::make_unique<ByteArray>(new ByteArray(request->q.get()));
  425. tl_p_q_inner_data_temp->new_nonce = std::make_unique<ByteArray>(new ByteArray(32));
  426. if (handshakeType == HandshakeTypeMediaTemp) {
  427. if (ConnectionsManager::getInstance(currentDatacenter->instanceNum).testBackend) {
  428. tl_p_q_inner_data_temp->dc = -(10000 + currentDatacenter->datacenterId);
  429. } else {
  430. tl_p_q_inner_data_temp->dc = -currentDatacenter->datacenterId;
  431. }
  432. } else {
  433. if (ConnectionsManager::getInstance(currentDatacenter->instanceNum).testBackend) {
  434. tl_p_q_inner_data_temp->dc = 10000 + currentDatacenter->datacenterId;
  435. } else {
  436. tl_p_q_inner_data_temp->dc = currentDatacenter->datacenterId;
  437. }
  438. }
  439. tl_p_q_inner_data_temp->expires_in = TEMP_AUTH_KEY_EXPIRE_TIME;
  440. RAND_bytes(tl_p_q_inner_data_temp->new_nonce->bytes, 32);
  441. authNewNonce = new ByteArray(tl_p_q_inner_data_temp->new_nonce.get());
  442. innerData = tl_p_q_inner_data_temp;
  443. }
  444. uint32_t innerDataSize = innerData->getObjectSize();
  445. if (innerDataSize > 144) {
  446. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: inner data too large %d, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, innerDataSize, handshakeType);
  447. delete innerData;
  448. beginHandshake(false);
  449. return;
  450. }
  451. uint32_t keySize = 32;
  452. uint32_t ivSize = 32;
  453. uint32_t paddedDataSize = 192;
  454. uint32_t encryptedDataSize = keySize + paddedDataSize + SHA256_DIGEST_LENGTH;
  455. uint32_t additionalSize = innerDataSize < paddedDataSize ? paddedDataSize - innerDataSize : 0;
  456. NativeByteBuffer *innerDataBuffer = BuffersStorage::getInstance().getFreeBuffer(encryptedDataSize + paddedDataSize + ivSize + SHA256_DIGEST_LENGTH + 256);
  457. innerDataBuffer->position(encryptedDataSize);
  458. innerData->serializeToStream(innerDataBuffer);
  459. delete innerData;
  460. BIO *keyBio = BIO_new(BIO_s_mem());
  461. BIO_write(keyBio, key.c_str(), (int) key.length());
  462. RSA *rsaKey = PEM_read_bio_RSAPublicKey(keyBio, nullptr, nullptr, nullptr);
  463. BIO_free(keyBio);
  464. while (true) {
  465. RAND_bytes(innerDataBuffer->bytes() + encryptedDataSize + innerDataSize, additionalSize);
  466. for (uint32_t i = 0; i < paddedDataSize; i++) {
  467. innerDataBuffer->bytes()[keySize + i] = innerDataBuffer->bytes()[encryptedDataSize + paddedDataSize - i - 1];
  468. }
  469. RAND_bytes(innerDataBuffer->bytes(), keySize);
  470. SHA256_CTX sha256Ctx;
  471. SHA256_Init(&sha256Ctx);
  472. SHA256_Update(&sha256Ctx, innerDataBuffer->bytes(), keySize);
  473. SHA256_Update(&sha256Ctx, innerDataBuffer->bytes() + encryptedDataSize, paddedDataSize);
  474. SHA256_Final(innerDataBuffer->bytes() + keySize + paddedDataSize, &sha256Ctx);
  475. memset(innerDataBuffer->bytes() + encryptedDataSize + paddedDataSize, 0, ivSize);
  476. Datacenter::aesIgeEncryption(innerDataBuffer->bytes() + keySize, innerDataBuffer->bytes(), innerDataBuffer->bytes() + encryptedDataSize + paddedDataSize, true, true, paddedDataSize + SHA256_DIGEST_LENGTH);
  477. SHA256_Init(&sha256Ctx);
  478. SHA256_Update(&sha256Ctx, innerDataBuffer->bytes() + keySize, paddedDataSize + SHA256_DIGEST_LENGTH);
  479. SHA256_Final(innerDataBuffer->bytes() + encryptedDataSize + paddedDataSize + ivSize, &sha256Ctx);
  480. for (uint32_t i = 0; i < keySize; i++) {
  481. innerDataBuffer->bytes()[i] ^= innerDataBuffer->bytes()[encryptedDataSize + paddedDataSize + ivSize + i];
  482. }
  483. bool ok = false;
  484. uint32_t offset = encryptedDataSize + paddedDataSize + ivSize + SHA256_DIGEST_LENGTH;
  485. size_t resLen = BN_bn2bin(rsaKey->n, innerDataBuffer->bytes() + offset);
  486. const auto shift = (256 - resLen);
  487. for (auto i = 0; i != 256; ++i) {
  488. const auto a = innerDataBuffer->bytes()[i];
  489. const auto b = (i < shift) ? 0 : innerDataBuffer->bytes()[offset + i - shift];
  490. if (a > b) {
  491. break;
  492. } else if (a < b) {
  493. ok = true;
  494. break;
  495. }
  496. }
  497. if (ok) {
  498. break;
  499. }
  500. }
  501. if (bnContext == nullptr) {
  502. bnContext = BN_CTX_new();
  503. }
  504. BIGNUM *a = BN_bin2bn(innerDataBuffer->bytes(), encryptedDataSize, nullptr);
  505. BIGNUM *r = BN_new();
  506. BN_mod_exp(r, a, rsaKey->e, rsaKey->n, bnContext);
  507. uint32_t size = BN_num_bytes(r);
  508. auto rsaEncryptedData = new ByteArray(size >= 256 ? size : 256);
  509. BN_bn2bin(r, rsaEncryptedData->bytes + (size < 256 ? (256 - size) : 0));
  510. if (256 - size > 0) {
  511. memset(rsaEncryptedData->bytes, 0, 256 - size);
  512. }
  513. BN_free(a);
  514. BN_free(r);
  515. RSA_free(rsaKey);
  516. innerDataBuffer->reuse();
  517. request->encrypted_data = std::unique_ptr<ByteArray>(rsaEncryptedData);
  518. sendAckRequest(messageId);
  519. sendRequestData(request, true);
  520. } else {
  521. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: invalid client nonce, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  522. beginHandshake(false);
  523. }
  524. } else if (dynamic_cast<Server_DH_Params *>(message)) {
  525. if (typeInfo == typeid(TL_server_DH_params_ok)) {
  526. if (handshakeState != 2) {
  527. sendAckRequest(messageId);
  528. return;
  529. }
  530. handshakeState = 3;
  531. TL_server_DH_params_ok *result = (TL_server_DH_params_ok *) message;
  532. NativeByteBuffer *tmpAesKeyAndIv = BuffersStorage::getInstance().getFreeBuffer(84);
  533. NativeByteBuffer *newNonceAndServerNonce = BuffersStorage::getInstance().getFreeBuffer(authNewNonce->length + authServerNonce->length);
  534. newNonceAndServerNonce->writeBytes(authNewNonce);
  535. newNonceAndServerNonce->writeBytes(authServerNonce);
  536. SHA1(newNonceAndServerNonce->bytes(), newNonceAndServerNonce->limit(), tmpAesKeyAndIv->bytes());
  537. newNonceAndServerNonce->reuse();
  538. NativeByteBuffer *serverNonceAndNewNonce = BuffersStorage::getInstance().getFreeBuffer(authServerNonce->length + authNewNonce->length);
  539. serverNonceAndNewNonce->writeBytes(authServerNonce);
  540. serverNonceAndNewNonce->writeBytes(authNewNonce);
  541. SHA1(serverNonceAndNewNonce->bytes(), serverNonceAndNewNonce->limit(), tmpAesKeyAndIv->bytes() + 20);
  542. serverNonceAndNewNonce->reuse();
  543. NativeByteBuffer *newNonceAndNewNonce = BuffersStorage::getInstance().getFreeBuffer(authNewNonce->length + authNewNonce->length);
  544. newNonceAndNewNonce->writeBytes(authNewNonce);
  545. newNonceAndNewNonce->writeBytes(authNewNonce);
  546. SHA1(newNonceAndNewNonce->bytes(), newNonceAndNewNonce->limit(), tmpAesKeyAndIv->bytes() + 40);
  547. newNonceAndNewNonce->reuse();
  548. memcpy(tmpAesKeyAndIv->bytes() + 60, authNewNonce->bytes, 4);
  549. Datacenter::aesIgeEncryption(result->encrypted_answer->bytes, tmpAesKeyAndIv->bytes(), tmpAesKeyAndIv->bytes() + 32, false, false, result->encrypted_answer->length);
  550. bool hashVerified = false;
  551. for (uint32_t i = 0; i < 16; i++) {
  552. SHA1(result->encrypted_answer->bytes + SHA_DIGEST_LENGTH, result->encrypted_answer->length - i - SHA_DIGEST_LENGTH, tmpAesKeyAndIv->bytes() + 64);
  553. if (!memcmp(tmpAesKeyAndIv->bytes() + 64, result->encrypted_answer->bytes, SHA_DIGEST_LENGTH)) {
  554. hashVerified = true;
  555. break;
  556. }
  557. }
  558. if (!hashVerified) {
  559. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: can't decode DH params, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  560. beginHandshake(false);
  561. return;
  562. }
  563. bool error = false;
  564. NativeByteBuffer *answerWithHash = new NativeByteBuffer(result->encrypted_answer->bytes + SHA_DIGEST_LENGTH, result->encrypted_answer->length - SHA_DIGEST_LENGTH);
  565. uint32_t constructor = answerWithHash->readUint32(&error);
  566. TL_server_DH_inner_data *dhInnerData = TL_server_DH_inner_data::TLdeserialize(answerWithHash, constructor, currentDatacenter->instanceNum, error);
  567. delete answerWithHash;
  568. if (error) {
  569. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: can't parse decoded DH params, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  570. beginHandshake(false);
  571. return;
  572. }
  573. if (!authNonce->isEqualTo(dhInnerData->nonce.get())) {
  574. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: invalid DH nonce, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  575. beginHandshake(false);
  576. return;
  577. }
  578. if (!authServerNonce->isEqualTo(dhInnerData->server_nonce.get())) {
  579. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: invalid DH server nonce, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  580. beginHandshake(false);
  581. return;
  582. }
  583. BIGNUM *p = BN_bin2bn(dhInnerData->dh_prime->bytes, dhInnerData->dh_prime->length, NULL);
  584. if (p == nullptr) {
  585. if (LOGS_ENABLED) DEBUG_E("can't allocate BIGNUM p");
  586. exit(1);
  587. }
  588. if (!isGoodPrime(p, dhInnerData->g)) {
  589. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: bad prime, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  590. beginHandshake(false);
  591. BN_free(p);
  592. return;
  593. }
  594. BIGNUM *g_a = BN_new();
  595. if (g_a == nullptr) {
  596. if (LOGS_ENABLED) DEBUG_E("can't allocate BIGNUM g_a");
  597. exit(1);
  598. }
  599. BN_bin2bn(dhInnerData->g_a->bytes, dhInnerData->g_a->length, g_a);
  600. if (!isGoodGaAndGb(g_a, p)) {
  601. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: bad prime and g_a, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  602. beginHandshake(false);
  603. BN_free(p);
  604. BN_free(g_a);
  605. return;
  606. }
  607. BIGNUM *g = BN_new();
  608. if (g == nullptr) {
  609. if (LOGS_ENABLED) DEBUG_E("can't allocate BIGNUM g");
  610. exit(1);
  611. }
  612. if (!BN_set_word(g, dhInnerData->g)) {
  613. if (LOGS_ENABLED) DEBUG_E("OpenSSL error at BN_set_word(g_b, dhInnerData->g)");
  614. beginHandshake(false);
  615. BN_free(g);
  616. BN_free(g_a);
  617. BN_free(p);
  618. return;
  619. }
  620. thread_local static uint8_t bytes[256];
  621. RAND_bytes(bytes, 256);
  622. BIGNUM *b = BN_bin2bn(bytes, 256, NULL);
  623. if (b == nullptr) {
  624. if (LOGS_ENABLED) DEBUG_E("can't allocate BIGNUM b");
  625. exit(1);
  626. }
  627. BIGNUM *g_b = BN_new();
  628. if (!BN_mod_exp(g_b, g, b, p, bnContext)) {
  629. if (LOGS_ENABLED) DEBUG_E("OpenSSL error at BN_mod_exp(g_b, g, b, p, bnContext)");
  630. beginHandshake(false);
  631. BN_free(g);
  632. BN_free(g_a);
  633. BN_free(g_b);
  634. BN_free(b);
  635. BN_free(p);
  636. return;
  637. }
  638. TL_client_DH_inner_data *clientInnerData = new TL_client_DH_inner_data();
  639. clientInnerData->g_b = std::unique_ptr<ByteArray>(new ByteArray(BN_num_bytes(g_b)));
  640. BN_bn2bin(g_b, clientInnerData->g_b->bytes);
  641. clientInnerData->nonce = std::unique_ptr<ByteArray>(new ByteArray(authNonce));
  642. clientInnerData->server_nonce = std::unique_ptr<ByteArray>(new ByteArray(authServerNonce));
  643. clientInnerData->retry_id = 0;
  644. BN_free(g_b);
  645. BN_free(g);
  646. BIGNUM *authKeyNum = BN_new();
  647. BN_mod_exp(authKeyNum, g_a, b, p, bnContext);
  648. size_t l = BN_num_bytes(authKeyNum);
  649. handshakeAuthKey = new ByteArray(256);
  650. BN_bn2bin(authKeyNum, handshakeAuthKey->bytes);
  651. if (l < 256) {
  652. memmove(handshakeAuthKey->bytes + 256 - l, handshakeAuthKey->bytes, l);
  653. memset(handshakeAuthKey->bytes, 0, 256 - l);
  654. }
  655. BN_free(authKeyNum);
  656. BN_free(g_a);
  657. BN_free(b);
  658. BN_free(p);
  659. uint32_t clientInnerDataSize = clientInnerData->getObjectSize();
  660. uint32_t additionalSize = (clientInnerDataSize + SHA_DIGEST_LENGTH) % 16;
  661. if (additionalSize != 0) {
  662. additionalSize = 16 - additionalSize;
  663. }
  664. NativeByteBuffer *clientInnerDataBuffer = BuffersStorage::getInstance().getFreeBuffer(clientInnerDataSize + additionalSize + SHA_DIGEST_LENGTH);
  665. clientInnerDataBuffer->position(SHA_DIGEST_LENGTH);
  666. clientInnerData->serializeToStream(clientInnerDataBuffer);
  667. delete clientInnerData;
  668. SHA1(clientInnerDataBuffer->bytes() + SHA_DIGEST_LENGTH, clientInnerDataSize, clientInnerDataBuffer->bytes());
  669. if (additionalSize != 0) {
  670. RAND_bytes(clientInnerDataBuffer->bytes() + SHA_DIGEST_LENGTH + clientInnerDataSize, additionalSize);
  671. }
  672. TL_set_client_DH_params *setClientDhParams = new TL_set_client_DH_params();
  673. setClientDhParams->nonce = std::unique_ptr<ByteArray>(new ByteArray(authNonce));
  674. setClientDhParams->server_nonce = std::unique_ptr<ByteArray>(new ByteArray(authServerNonce));
  675. Datacenter::aesIgeEncryption(clientInnerDataBuffer->bytes(), tmpAesKeyAndIv->bytes(), tmpAesKeyAndIv->bytes() + 32, true, false, clientInnerDataBuffer->limit());
  676. setClientDhParams->encrypted_data = std::unique_ptr<ByteArray>(new ByteArray(clientInnerDataBuffer->bytes(), clientInnerDataBuffer->limit()));
  677. clientInnerDataBuffer->reuse();
  678. tmpAesKeyAndIv->reuse();
  679. sendAckRequest(messageId);
  680. sendRequestData(setClientDhParams, true);
  681. int32_t currentTime = (int32_t) (ConnectionsManager::getInstance(currentDatacenter->instanceNum).getCurrentTimeMillis() / 1000);
  682. timeDifference = dhInnerData->server_time - currentTime;
  683. handshakeServerSalt = new TL_future_salt();
  684. handshakeServerSalt->valid_since = currentTime + timeDifference - 5;
  685. handshakeServerSalt->valid_until = handshakeServerSalt->valid_since + 30 * 60;
  686. for (int32_t a = 7; a >= 0; a--) {
  687. handshakeServerSalt->salt <<= 8;
  688. handshakeServerSalt->salt |= (authNewNonce->bytes[a] ^ authServerNonce->bytes[a]);
  689. }
  690. } else {
  691. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: can't set DH params, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  692. beginHandshake(false);
  693. }
  694. } else if (dynamic_cast<Set_client_DH_params_answer *>(message)) {
  695. if (handshakeState != 3) {
  696. sendAckRequest(messageId);
  697. return;
  698. }
  699. handshakeState = 4;
  700. Set_client_DH_params_answer *result = (Set_client_DH_params_answer *) message;
  701. if (!authNonce->isEqualTo(result->nonce.get())) {
  702. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: invalid DH answer nonce, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  703. beginHandshake(false);
  704. return;
  705. }
  706. if (!authServerNonce->isEqualTo(result->server_nonce.get())) {
  707. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: invalid DH answer server nonce, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  708. beginHandshake(false);
  709. return;
  710. }
  711. sendAckRequest(messageId);
  712. uint32_t authKeyAuxHashLength = authNewNonce->length + SHA_DIGEST_LENGTH + 1;
  713. NativeByteBuffer *authKeyAuxHashBuffer = BuffersStorage::getInstance().getFreeBuffer(authKeyAuxHashLength + SHA_DIGEST_LENGTH);
  714. authKeyAuxHashBuffer->writeBytes(authNewNonce);
  715. SHA1(handshakeAuthKey->bytes, handshakeAuthKey->length, authKeyAuxHashBuffer->bytes() + authNewNonce->length + 1);
  716. if (typeInfo == typeid(TL_dh_gen_ok)) {
  717. authKeyAuxHashBuffer->writeByte(1);
  718. SHA1(authKeyAuxHashBuffer->bytes(), authKeyAuxHashLength - 12, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength);
  719. if (memcmp(result->new_nonce_hash1->bytes, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength + SHA_DIGEST_LENGTH - 16, 16)) {
  720. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: invalid DH answer nonce hash 1, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  721. authKeyAuxHashBuffer->reuse();
  722. beginHandshake(false);
  723. } else {
  724. if (LOGS_ENABLED) DEBUG_D("account%u dc%u handshake: completed, time difference = %d, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, timeDifference, handshakeType);
  725. authKeyAuxHashBuffer->position(authNewNonce->length + 1 + 12);
  726. authKeyTempPendingId = authKeyAuxHashBuffer->readInt64(nullptr);
  727. authKeyAuxHashBuffer->reuse();
  728. if (handshakeRequest != nullptr) {
  729. delete handshakeRequest;
  730. handshakeRequest = nullptr;
  731. }
  732. std::unique_ptr<TL_future_salt> salt = std::unique_ptr<TL_future_salt>(handshakeServerSalt);
  733. currentDatacenter->clearServerSalts(handshakeType == HandshakeTypeMediaTemp);
  734. currentDatacenter->addServerSalt(salt, handshakeType == HandshakeTypeMediaTemp);
  735. handshakeServerSalt = nullptr;
  736. if (handshakeType == HandshakeTypePerm) {
  737. ConnectionsManager::getInstance(currentDatacenter->instanceNum).scheduleTask([&] {
  738. ByteArray *authKey = handshakeAuthKey;
  739. handshakeAuthKey = nullptr;
  740. delegate->onHandshakeComplete(this, authKeyTempPendingId, authKey, timeDifference);
  741. });
  742. } else {
  743. authKeyTempPending = handshakeAuthKey;
  744. handshakeAuthKey = nullptr;
  745. Connection *connection = getConnection();
  746. TL_auth_bindTempAuthKey *request = new TL_auth_bindTempAuthKey();
  747. request->initFunc = [&, request, connection](int64_t messageId) {
  748. TL_bind_auth_key_inner *inner = new TL_bind_auth_key_inner();
  749. inner->expires_at = ConnectionsManager::getInstance(currentDatacenter->instanceNum).getCurrentTime() + timeDifference + TEMP_AUTH_KEY_EXPIRE_TIME;
  750. inner->perm_auth_key_id = currentDatacenter->authKeyPermId;
  751. inner->temp_auth_key_id = authKeyTempPendingId;
  752. RAND_bytes((uint8_t *) &inner->nonce, 8);
  753. inner->temp_session_id = connection->getSessionId();
  754. NetworkMessage *networkMessage = new NetworkMessage();
  755. networkMessage->message = std::make_unique<TL_message>();
  756. networkMessage->message->msg_id = authKeyPendingMessageId = messageId;
  757. networkMessage->message->bytes = inner->getObjectSize();
  758. networkMessage->message->body = std::unique_ptr<TLObject>(inner);
  759. networkMessage->message->seqno = 0;
  760. std::vector<std::unique_ptr<NetworkMessage>> array;
  761. array.push_back(std::unique_ptr<NetworkMessage>(networkMessage));
  762. request->perm_auth_key_id = inner->perm_auth_key_id;
  763. request->nonce = inner->nonce;
  764. request->expires_at = inner->expires_at;
  765. request->encrypted_message = currentDatacenter->createRequestsData(array, nullptr, connection, true);
  766. };
  767. authKeyPendingRequestId = ConnectionsManager::getInstance(currentDatacenter->instanceNum).sendRequest(request, [&](TLObject *response, TL_error *error, int32_t networkType, int64_t responseTime) {
  768. authKeyPendingMessageId = 0;
  769. authKeyPendingRequestId = 0;
  770. if (response != nullptr && typeid(*response) == typeid(TL_boolTrue)) {
  771. if (LOGS_ENABLED) DEBUG_D("account%u dc%u handshake: bind completed", currentDatacenter->instanceNum, currentDatacenter->datacenterId);
  772. ConnectionsManager::getInstance(currentDatacenter->instanceNum).scheduleTask([&] {
  773. ByteArray *authKey = authKeyTempPending;
  774. authKeyTempPending = nullptr;
  775. delegate->onHandshakeComplete(this, authKeyTempPendingId, authKey, timeDifference);
  776. });
  777. } else if (error == nullptr || error->code != 400 || error->text.find("ENCRYPTED_MESSAGE_INVALID") == std::string::npos) {
  778. ConnectionsManager::getInstance(currentDatacenter->instanceNum).scheduleTask([&] {
  779. beginHandshake(true);
  780. });
  781. }
  782. }, nullptr, RequestFlagWithoutLogin | RequestFlagEnableUnauthorized | RequestFlagUseUnboundKey, currentDatacenter->datacenterId, connection->getConnectionType(), true, 0);
  783. }
  784. }
  785. } else if (typeInfo == typeid(TL_dh_gen_retry)) {
  786. authKeyAuxHashBuffer->writeByte(2);
  787. SHA1(authKeyAuxHashBuffer->bytes(), authKeyAuxHashLength - 12, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength);
  788. if (memcmp(result->new_nonce_hash2->bytes, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength + SHA_DIGEST_LENGTH - 16, 16)) {
  789. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: invalid DH answer nonce hash 2, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  790. beginHandshake(false);
  791. } else {
  792. if (LOGS_ENABLED) DEBUG_D("account%u dc%u handshake: retry DH, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  793. beginHandshake(false);
  794. }
  795. authKeyAuxHashBuffer->reuse();
  796. } else if (typeInfo == typeid(TL_dh_gen_fail)) {
  797. authKeyAuxHashBuffer->writeByte(3);
  798. SHA1(authKeyAuxHashBuffer->bytes(), authKeyAuxHashLength - 12, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength);
  799. if (memcmp(result->new_nonce_hash3->bytes, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength + SHA_DIGEST_LENGTH - 16, 16)) {
  800. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: invalid DH answer nonce hash 3, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  801. beginHandshake(false);
  802. } else {
  803. if (LOGS_ENABLED) DEBUG_E("account%u dc%u handshake: server declined DH params, type = %d", currentDatacenter->instanceNum, currentDatacenter->datacenterId, handshakeType);
  804. beginHandshake(false);
  805. }
  806. authKeyAuxHashBuffer->reuse();
  807. }
  808. }
  809. }
  810. void Handshake::sendAckRequest(int64_t messageId) {
  811. auto msgsAck = new TL_msgs_ack();
  812. msgsAck->msg_ids.push_back(messageId);
  813. sendRequestData(msgsAck, false);
  814. }
  815. TLObject *Handshake::getCurrentHandshakeRequest() {
  816. return handshakeRequest;
  817. }
  818. void Handshake::saveCdnConfigInternal(NativeByteBuffer *buffer) {
  819. buffer->writeInt32(1);
  820. buffer->writeInt32((int32_t) cdnPublicKeys.size());
  821. for (auto & cdnPublicKey : cdnPublicKeys) {
  822. buffer->writeInt32(cdnPublicKey.first);
  823. buffer->writeString(cdnPublicKey.second);
  824. buffer->writeInt64(cdnPublicKeysFingerprints[cdnPublicKey.first]);
  825. }
  826. }
  827. void Handshake::saveCdnConfig(Datacenter *datacenter) {
  828. if (cdnConfig == nullptr) {
  829. cdnConfig = new Config(datacenter->instanceNum, "cdnkeys.dat");
  830. }
  831. thread_local static auto sizeCalculator = new NativeByteBuffer(true);
  832. sizeCalculator->clearCapacity();
  833. saveCdnConfigInternal(sizeCalculator);
  834. NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(sizeCalculator->capacity());
  835. saveCdnConfigInternal(buffer);
  836. cdnConfig->writeConfig(buffer);
  837. buffer->reuse();
  838. }
  839. void Handshake::loadCdnConfig(Datacenter *datacenter) {
  840. if (std::find(cdnWaitingDatacenters.begin(), cdnWaitingDatacenters.end(), datacenter) != cdnWaitingDatacenters.end()) {
  841. return;
  842. }
  843. cdnWaitingDatacenters.push_back(datacenter);
  844. if (loadingCdnKeys) {
  845. return;
  846. }
  847. if (cdnPublicKeysFingerprints.empty()) {
  848. if (cdnConfig == nullptr) {
  849. cdnConfig = new Config(datacenter->instanceNum, "cdnkeys.dat");
  850. }
  851. NativeByteBuffer *buffer = cdnConfig->readConfig();
  852. if (buffer != nullptr) {
  853. uint32_t version = buffer->readUint32(nullptr);
  854. if (version >= 1) {
  855. size_t count = buffer->readUint32(nullptr);
  856. for (uint32_t a = 0; a < count; a++) {
  857. int dcId = buffer->readInt32(nullptr);
  858. cdnPublicKeys[dcId] = buffer->readString(nullptr);
  859. cdnPublicKeysFingerprints[dcId] = buffer->readUint64(nullptr);
  860. }
  861. }
  862. buffer->reuse();
  863. if (!cdnPublicKeysFingerprints.empty()) {
  864. size_t count = cdnWaitingDatacenters.size();
  865. for (uint32_t a = 0; a < count; a++) {
  866. cdnWaitingDatacenters[a]->beginHandshake(HandshakeTypeCurrent, false);
  867. }
  868. cdnWaitingDatacenters.clear();
  869. return;
  870. }
  871. }
  872. }
  873. loadingCdnKeys = true;
  874. auto request = new TL_help_getCdnConfig();
  875. ConnectionsManager::getInstance(datacenter->instanceNum).sendRequest(request, [&, datacenter](TLObject *response, TL_error *error, int32_t networkType, int64_t responseTime) {
  876. if (response != nullptr) {
  877. auto config = (TL_cdnConfig *) response;
  878. size_t count = config->public_keys.size();
  879. BIO *keyBio = BIO_new(BIO_s_mem());
  880. NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(1024);
  881. thread_local static uint8_t sha1Buffer[20];
  882. for (uint32_t a = 0; a < count; a++) {
  883. TL_cdnPublicKey *publicKey = config->public_keys[a].get();
  884. cdnPublicKeys[publicKey->dc_id] = publicKey->public_key;
  885. BIO_write(keyBio, publicKey->public_key.c_str(), (int) publicKey->public_key.length());
  886. RSA *rsaKey = PEM_read_bio_RSAPublicKey(keyBio, nullptr, nullptr, nullptr);
  887. int nBytes = BN_num_bytes(rsaKey->n);
  888. int eBytes = BN_num_bytes(rsaKey->e);
  889. std::string nStr(nBytes, 0), eStr(eBytes, 0);
  890. BN_bn2bin(rsaKey->n, (uint8_t *)&nStr[0]);
  891. BN_bn2bin(rsaKey->e, (uint8_t *)&eStr[0]);
  892. buffer->writeString(nStr);
  893. buffer->writeString(eStr);
  894. SHA1(buffer->bytes(), buffer->position(), sha1Buffer);
  895. cdnPublicKeysFingerprints[publicKey->dc_id] = ((uint64_t) sha1Buffer[19]) << 56 |
  896. ((uint64_t) sha1Buffer[18]) << 48 |
  897. ((uint64_t) sha1Buffer[17]) << 40 |
  898. ((uint64_t) sha1Buffer[16]) << 32 |
  899. ((uint64_t) sha1Buffer[15]) << 24 |
  900. ((uint64_t) sha1Buffer[14]) << 16 |
  901. ((uint64_t) sha1Buffer[13]) << 8 |
  902. ((uint64_t) sha1Buffer[12]);
  903. RSA_free(rsaKey);
  904. if (a != count - 1) {
  905. buffer->position(0);
  906. BIO_reset(keyBio);
  907. }
  908. }
  909. buffer->reuse();
  910. BIO_free(keyBio);
  911. count = cdnWaitingDatacenters.size();
  912. for (uint32_t a = 0; a < count; a++) {
  913. cdnWaitingDatacenters[a]->beginHandshake(HandshakeTypeCurrent, false);
  914. }
  915. cdnWaitingDatacenters.clear();
  916. saveCdnConfig(datacenter);
  917. }
  918. loadingCdnKeys = false;
  919. }, nullptr, RequestFlagEnableUnauthorized | RequestFlagWithoutLogin, DEFAULT_DATACENTER_ID, ConnectionTypeGeneric, true);
  920. }
  921. HandshakeType Handshake::getType() {
  922. return handshakeType;
  923. }
  924. ByteArray *Handshake::getPendingAuthKey() {
  925. return authKeyTempPending;
  926. }
  927. int64_t Handshake::getPendingAuthKeyId() {
  928. return authKeyTempPendingId;
  929. }
  930. void Handshake::onHandshakeConnectionClosed() {
  931. if (handshakeState == 0) {
  932. return;
  933. }
  934. needResendData = true;
  935. }
  936. void Handshake::onHandshakeConnectionConnected() {
  937. if (handshakeState == 0 || !needResendData) {
  938. return;
  939. }
  940. beginHandshake(false);
  941. }