| 6 |
| * Copyright Nikolai Kudashov, 2015-2018. |
| 7 | */ |
| 8 |
| 9 | #include <stdlib.h> |
| 10 | #include <algorithm> |
| 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 |
| 28 | thread_local static std::vector<std::string> serverPublicKeys; |
| 29 | thread_local static std::vector<uint64_t> serverPublicKeysFingerprints; |
| 30 | thread_local static std::map<int32_t, std::string> cdnPublicKeys; |
| 31 | thread_local static std::map<int32_t, uint64_t> cdnPublicKeysFingerprints; |
| 32 | thread_local static std::vector<Datacenter *> cdnWaitingDatacenters; |
| 33 | thread_local static bool loadingCdnKeys = false; |
| 34 | thread_local static BN_CTX *bnContext = nullptr; |
| 35 | thread_local static Config *cdnConfig = nullptr; |
| 36 |
| 37 | Handshake::Handshake(Datacenter *datacenter, HandshakeType type, HandshakeDelegate *handshakeDelegate) { |
| 38 | currentDatacenter = datacenter; |
| 39 | handshakeType = type; |
| 40 | delegate = handshakeDelegate; |
| 41 | } |
| 42 |
| 43 | Handshake::~Handshake() { |
| 44 | cleanupHandshake(); |
| 45 | } |
| 46 |
| 47 | void Handshake::beginHandshake(bool reconnect) { |
| 48 | if (LOGS_ENABLED) DEBUG_D("dc%u handshake: begin, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 49 | cleanupHandshake(); |
| 50 | Connection *connection = getConnection(); |
| 51 | handshakeState = 1; |
| 52 |
| 53 | if (reconnect) { |
| 54 | connection->suspendConnection(); |
| 55 | connection->connect(); |
| 56 | } |
| 57 |
| 58 | #ifdef USE_OLD_KEYS |
| 59 | TL_req_pq *request = new TL_req_pq(); |
| 60 | request->nonce = std::unique_ptr<ByteArray>(new ByteArray(16)); |
| 61 | RAND_bytes(request->nonce->bytes, 16); |
| 62 | authNonce = new ByteArray(request->nonce.get()); |
| 63 | sendRequestData(request, true); |
| 64 | #else |
| 65 | TL_req_pq_multi *request = new TL_req_pq_multi(); |
| 66 | request->nonce = std::unique_ptr<ByteArray>(new ByteArray(16)); |
| 67 | RAND_bytes(request->nonce->bytes, 16); |
| 68 | authNonce = new ByteArray(request->nonce.get()); |
| 69 | sendRequestData(request, true); |
| 70 | #endif |
| 71 | } |
| 72 |
| 73 | void Handshake::cleanupHandshake() { |
| 74 | handshakeState = 0; |
| 75 | if (handshakeRequest != nullptr) { |
| 76 | delete handshakeRequest; |
| 77 | handshakeRequest = nullptr; |
| 78 | } |
| 79 | if (handshakeServerSalt != nullptr) { |
| 80 | delete handshakeServerSalt; |
| 81 | handshakeServerSalt = nullptr; |
| 82 | } |
| 83 | if (authNonce != nullptr) { |
| 84 | delete authNonce; |
| 85 | authNonce = nullptr; |
| 86 | } |
| 87 | if (authServerNonce != nullptr) { |
| 88 | delete authServerNonce; |
| 89 | authServerNonce = nullptr; |
| 90 | } |
| 91 | if (authNewNonce != nullptr) { |
| 92 | delete authNewNonce; |
| 93 | authNewNonce = nullptr; |
| 94 | } |
| 95 | if (handshakeAuthKey != nullptr) { |
| 96 | delete handshakeAuthKey; |
| 97 | handshakeAuthKey = nullptr; |
| 98 | } |
| 99 | if (authKeyTempPending != nullptr) { |
| 100 | delete authKeyTempPending; |
| 101 | authKeyTempPending = nullptr; |
| 102 | } |
| 103 | if (authKeyPendingMessageId != 0 || authKeyPendingRequestId != 0) { |
| 104 | ConnectionsManager::getInstance(currentDatacenter->instanceNum).cancelRequestInternal(authKeyPendingRequestId, authKeyPendingMessageId, false, false); |
| 105 | authKeyPendingMessageId = 0; |
| 106 | authKeyPendingRequestId = 0; |
| 107 | } |
| 108 | authKeyTempPendingId = 0; |
| 109 | } |
| 110 |
| 111 | inline Connection *Handshake::getConnection() { |
| 112 | return handshakeType == HandshakeTypeMediaTemp ? currentDatacenter->createGenericMediaConnection() : currentDatacenter->createGenericConnection(); |
| 113 | } |
| 114 |
| 115 | void Handshake::sendRequestData(TLObject *object, bool important) { |
| 116 | uint32_t messageLength = object->getObjectSize(); |
| 117 | NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(20 + messageLength); |
| 118 | buffer->writeInt64(0); |
| 119 | buffer->writeInt64(ConnectionsManager::getInstance(currentDatacenter->instanceNum).generateMessageId()); |
| 120 | buffer->writeInt32(messageLength); |
| 121 | object->serializeToStream(buffer); |
| 122 | getConnection()->sendData(buffer, false, false); |
| 123 | if (important) { |
| 124 | if (handshakeRequest != object) { |
| 125 | if (handshakeRequest != nullptr) { |
| 126 | delete handshakeRequest; |
| 127 | } |
| 128 | handshakeRequest = object; |
| 129 | } |
| 130 | } else { |
| 131 | delete object; |
| 132 | } |
| 133 | } |
| 134 |
| 135 | inline uint64_t gcd(uint64_t a, uint64_t b) { |
| 136 | while (a != 0 && b != 0) { |
| 137 | while ((b & 1) == 0) { |
| 138 | b >>= 1; |
| 139 | } |
| 140 | while ((a & 1) == 0) { |
| 141 | a >>= 1; |
| 142 | } |
| 143 | if (a > b) { |
| 144 | a -= b; |
| 145 | } else { |
| 146 | b -= a; |
| 147 | } |
| 148 | } |
| 149 | return b == 0 ? a : b; |
| 150 | } |
| 151 |
| 152 | inline bool factorizeValue(uint64_t what, uint32_t &p, uint32_t &q) { |
| 153 | int32_t it = 0, i, j; |
| 154 | uint64_t g = 0; |
| 155 | for (i = 0; i < 3 || it < 1000; i++) { |
| 156 | uint64_t t = ((lrand48() & 15) + 17) % what; |
| 157 | uint64_t x = (long long) lrand48() % (what - 1) + 1, y = x; |
| 158 | int32_t lim = 1 << (i + 18); |
| 159 | for (j = 1; j < lim; j++) { |
| 160 | ++it; |
| 161 | uint64_t a = x, b = x, c = t; |
| 162 | while (b) { |
| 163 | if (b & 1) { |
| 164 | c += a; |
| 165 | if (c >= what) { |
| 166 | c -= what; |
| 167 | } |
| 168 | } |
| 169 | a += a; |
| 170 | if (a >= what) { |
| 171 | a -= what; |
| 172 | } |
| 173 | b >>= 1; |
| 174 | } |
| 175 | x = c; |
| 176 | uint64_t z = x < y ? what + x - y : x - y; |
| 177 | g = gcd(z, what); |
| 178 | if (g != 1) { |
| 179 | break; |
| 180 | } |
| 181 | if (!(j & (j - 1))) { |
| 182 | y = x; |
| 183 | } |
| 184 | } |
| 185 | if (g > 1 && g < what) { |
| 186 | break; |
| 187 | } |
| 188 | } |
| 189 |
| 190 | if (g > 1 && g < what) { |
| 191 | p = (uint32_t) g; |
| 192 | q = (uint32_t) (what / g); |
| 193 | if (p > q) { |
| 194 | uint32_t tmp = p; |
| 195 | p = q; |
| 196 | q = tmp; |
| 197 | } |
| 198 | return true; |
| 199 | } else { |
| 200 | if (LOGS_ENABLED) DEBUG_E("factorization failed for %" PRIu64, what); |
| 201 | p = 0; |
| 202 | q = 0; |
| 203 | return false; |
| 204 | } |
| 205 | } |
| 206 |
| 207 | inline bool check_prime(BIGNUM *p) { |
| 208 | int result = 0; |
| 209 | if (!BN_primality_test(&result, p, BN_prime_checks, bnContext, 0, NULL)) { |
| 210 | if (LOGS_ENABLED) DEBUG_E("OpenSSL error at BN_primality_test"); |
| 211 | return false; |
| 212 | } |
| 213 | return result != 0; |
| 214 | } |
| 215 |
| 216 | inline bool isGoodPrime(BIGNUM *p, uint32_t g) { |
| 217 | if (g < 2 || g > 7 || BN_num_bits(p) != 2048) { |
| 218 | return false; |
| 219 | } |
| 220 |
| 221 | BIGNUM *t = BN_new(); |
| 222 | BIGNUM *dh_g = BN_new(); |
| 223 |
| 224 | if (!BN_set_word(dh_g, 4 * g)) { |
| 225 | if (LOGS_ENABLED) DEBUG_E("OpenSSL error at BN_set_word(dh_g, 4 * g)"); |
| 226 | BN_free(t); |
| 227 | BN_free(dh_g); |
| 228 | return false; |
| 229 | } |
| 230 | if (!BN_mod(t, p, dh_g, bnContext)) { |
| 231 | if (LOGS_ENABLED) DEBUG_E("OpenSSL error at BN_mod"); |
| 232 | BN_free(t); |
| 233 | BN_free(dh_g); |
| 234 | return false; |
| 235 | } |
| 236 | uint64_t x = BN_get_word(t); |
| 237 | if (x >= 4 * g) { |
| 238 | if (LOGS_ENABLED) DEBUG_E("OpenSSL error at BN_get_word"); |
| 239 | BN_free(t); |
| 240 | BN_free(dh_g); |
| 241 | return false; |
| 242 | } |
| 243 |
| 244 | BN_free(dh_g); |
| 245 |
| 246 | bool result = true; |
| 247 | switch (g) { |
| 248 | case 2: |
| 249 | if (x != 7) { |
| 250 | result = false; |
| 251 | } |
| 252 | break; |
| 253 | case 3: |
| 254 | if (x % 3 != 2) { |
| 255 | result = false; |
| 256 | } |
| 257 | break; |
| 258 | case 5: |
| 259 | if (x % 5 != 1 && x % 5 != 4) { |
| 260 | result = false; |
| 261 | } |
| 262 | break; |
| 263 | case 6: |
| 264 | if (x != 19 && x != 23) { |
| 265 | result = false; |
| 266 | } |
| 267 | break; |
| 268 | case 7: |
| 269 | if (x % 7 != 3 && x % 7 != 5 && x % 7 != 6) { |
| 270 | result = false; |
| 271 | } |
| 272 | break; |
| 273 | default: |
| 274 | break; |
| 275 | } |
| 276 |
| 277 | char *prime = BN_bn2hex(p); |
| 278 | static const char *goodPrime = "c71caeb9c6b1c9048e6c522f70f13f73980d40238e3e21c14934d037563d930f48198a0aa7c14058229493d22530f4dbfa336f6e0ac925139543aed44cce7c3720fd51f69458705ac68cd4fe6b6b13abdc9746512969328454f18faf8c595f642477fe96bb2a941d5bcd1d4ac8cc49880708fa9b378e3c4f3a9060bee67cf9a4a4a695811051907e162753b56b0f6b410dba74d8a84b2a14b3144e0ef1284754fd17ed950d5965b4b9dd46582db1178d169c6bc465b0d6ff9ca3928fef5b9ae4e418fc15e83ebea0f87fa9ff5eed70050ded2849f47bf959d956850ce929851f0d8115f635b105ee2e4e15d04b2454bf6f4fadf034b10403119cd8e3b92fcc5b"; |
| 279 | if (!strcasecmp(prime, goodPrime)) { |
| 280 | OPENSSL_free(prime); |
| 281 | BN_free(t); |
| 282 | return true; |
| 283 | } |
| 284 | OPENSSL_free(prime); |
| 285 |
| 286 | if (!result || !check_prime(p)) { |
| 287 | BN_free(t); |
| 288 | return false; |
| 289 | } |
| 290 |
| 291 | BIGNUM *b = BN_new(); |
| 292 | if (!BN_set_word(b, 2)) { |
| 293 | if (LOGS_ENABLED) DEBUG_E("OpenSSL error at BN_set_word(b, 2)"); |
| 294 | BN_free(b); |
| 295 | BN_free(t); |
| 296 | return false; |
| 297 | } |
| 298 | if (!BN_div(t, 0, p, b, bnContext)) { |
| 299 | if (LOGS_ENABLED) DEBUG_E("OpenSSL error at BN_div"); |
| 300 | BN_free(b); |
| 301 | BN_free(t); |
| 302 | return false; |
| 303 | } |
| 304 | if (!check_prime(t)) { |
| 305 | result = false; |
| 306 | } |
| 307 | BN_free(b); |
| 308 | BN_free(t); |
| 309 | return result; |
| 310 | } |
| 311 |
| 312 | inline bool isGoodGaAndGb(BIGNUM *g_a, BIGNUM *p) { |
| 313 | if (BN_num_bytes(g_a) > 256 || BN_num_bits(g_a) < 2048 - 64 || BN_cmp(p, g_a) <= 0) { |
| 314 | return false; |
| 315 | } |
| 316 | BIGNUM *dif = BN_new(); |
| 317 | BN_sub(dif, p, g_a); |
| 318 | if (BN_num_bits(dif) < 2048 - 64) { |
| 319 | BN_free(dif); |
| 320 | return false; |
| 321 | } |
| 322 | BN_free(dif); |
| 323 | return true; |
| 324 | } |
| 325 |
| 326 | void Handshake::processHandshakeResponse(TLObject *message, int64_t messageId) { |
| 327 | if (handshakeState == 0) { |
| 328 | return; |
| 329 | } |
| 330 | const std::type_info &typeInfo = typeid(*message); |
| 331 | if (typeInfo == typeid(TL_resPQ)) { |
| 332 | if (handshakeState != 1) { |
| 333 | sendAckRequest(messageId); |
| 334 | return; |
| 335 | } |
| 336 |
| 337 | handshakeState = 2; |
| 338 | TL_resPQ *result = (TL_resPQ *) message; |
| 339 | if (authNonce->isEqualTo(result->nonce.get())) { |
| 340 | std::string key; |
| 341 | int64_t keyFingerprint = 0; |
| 342 |
| 343 | size_t count1 = result->server_public_key_fingerprints.size(); |
| 344 | if (currentDatacenter->isCdnDatacenter) { |
| 345 | std::map<int32_t, uint64_t>::iterator iter = cdnPublicKeysFingerprints.find(currentDatacenter->datacenterId); |
| 346 | if (iter != cdnPublicKeysFingerprints.end()) { |
| 347 | for (uint32_t a = 0; a < count1; a++) { |
| 348 | if ((uint64_t) result->server_public_key_fingerprints[a] == iter->second) { |
| 349 | keyFingerprint = iter->second; |
| 350 | key = cdnPublicKeys[currentDatacenter->datacenterId]; |
| 351 | } |
| 352 | } |
| 353 | } |
| 354 | } else { |
| 355 | if (serverPublicKeys.empty()) { |
| 356 | #ifdef USE_OLD_KEYS |
| 357 | serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" |
| 358 | "MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6\n" |
| 359 | "lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS\n" |
| 360 | "an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw\n" |
| 361 | "Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+\n" |
| 362 | "8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n\n" |
| 363 | "Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB\n" |
| 364 | "-----END RSA PUBLIC KEY-----"); |
| 365 | serverPublicKeysFingerprints.push_back(0xc3b42b026ce86b21LL); |
| 366 |
| 367 | serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" |
| 368 | "MIIBCgKCAQEAxq7aeLAqJR20tkQQMfRn+ocfrtMlJsQ2Uksfs7Xcoo77jAid0bRt\n" |
| 369 | "ksiVmT2HEIJUlRxfABoPBV8wY9zRTUMaMA654pUX41mhyVN+XoerGxFvrs9dF1Ru\n" |
| 370 | "vCHbI02dM2ppPvyytvvMoefRoL5BTcpAihFgm5xCaakgsJ/tH5oVl74CdhQw8J5L\n" |
| 371 | "xI/K++KJBUyZ26Uba1632cOiq05JBUW0Z2vWIOk4BLysk7+U9z+SxynKiZR3/xdi\n" |
| 372 | "XvFKk01R3BHV+GUKM2RYazpS/P8v7eyKhAbKxOdRcFpHLlVwfjyM1VlDQrEZxsMp\n" |
| 373 | "NTLYXb6Sce1Uov0YtNx5wEowlREH1WOTlwIDAQAB\n" |
| 374 | "-----END RSA PUBLIC KEY-----"); |
| 375 | serverPublicKeysFingerprints.push_back(0x9a996a1db11c729bLL); |
| 376 |
| 377 | serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" |
| 378 | "MIIBCgKCAQEAsQZnSWVZNfClk29RcDTJQ76n8zZaiTGuUsi8sUhW8AS4PSbPKDm+\n" |
| 379 | "DyJgdHDWdIF3HBzl7DHeFrILuqTs0vfS7Pa2NW8nUBwiaYQmPtwEa4n7bTmBVGsB\n" |
| 380 | "1700/tz8wQWOLUlL2nMv+BPlDhxq4kmJCyJfgrIrHlX8sGPcPA4Y6Rwo0MSqYn3s\n" |
| 381 | "g1Pu5gOKlaT9HKmE6wn5Sut6IiBjWozrRQ6n5h2RXNtO7O2qCDqjgB2vBxhV7B+z\n" |
| 382 | "hRbLbCmW0tYMDsvPpX5M8fsO05svN+lKtCAuz1leFns8piZpptpSCFn7bWxiA9/f\n" |
| 383 | "x5x17D7pfah3Sy2pA+NDXyzSlGcKdaUmwQIDAQAB\n" |
| 384 | "-----END RSA PUBLIC KEY-----"); |
| 385 | serverPublicKeysFingerprints.push_back(0xb05b2a6f70cdea78LL); |
| 386 |
| 387 | serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" |
| 388 | "MIIBCgKCAQEAwqjFW0pi4reKGbkc9pK83Eunwj/k0G8ZTioMMPbZmW99GivMibwa\n" |
| 389 | "xDM9RDWabEMyUtGoQC2ZcDeLWRK3W8jMP6dnEKAlvLkDLfC4fXYHzFO5KHEqF06i\n" |
| 390 | "qAqBdmI1iBGdQv/OQCBcbXIWCGDY2AsiqLhlGQfPOI7/vvKc188rTriocgUtoTUc\n" |
| 391 | "/n/sIUzkgwTqRyvWYynWARWzQg0I9olLBBC2q5RQJJlnYXZwyTL3y9tdb7zOHkks\n" |
| 392 | "WV9IMQmZmyZh/N7sMbGWQpt4NMchGpPGeJ2e5gHBjDnlIf2p1yZOYeUYrdbwcS0t\n" |
| 393 | "UiggS4UeE8TzIuXFQxw7fzEIlmhIaq3FnwIDAQAB\n" |
| 394 | "-----END RSA PUBLIC KEY-----"); |
| 395 | serverPublicKeysFingerprints.push_back(0x71e025b6c76033e3LL); |
| 396 | #endif |
| 397 |
| 398 | serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" |
| 399 | "MIIBCgKCAQEAruw2yP/BCcsJliRoW5eBVBVle9dtjJw+OYED160Wybum9SXtBBLX\n" |
| 400 | "riwt4rROd9csv0t0OHCaTmRqBcQ0J8fxhN6/cpR1GWgOZRUAiQxoMnlt0R93LCX/\n" |
| 401 | "j1dnVa/gVbCjdSxpbrfY2g2L4frzjJvdl84Kd9ORYjDEAyFnEA7dD556OptgLQQ2\n" |
| 402 | "e2iVNq8NZLYTzLp5YpOdO1doK+ttrltggTCy5SrKeLoCPPbOgGsdxJxyz5KKcZnS\n" |
| 403 | "Lj16yE5HvJQn0CNpRdENvRUXe6tBP78O39oJ8BTHp9oIjd6XWXAsp2CvK45Ol8wF\n" |
| 404 | "XGF710w9lwCGNbmNxNYhtIkdqfsEcwR5JwIDAQAB\n" |
| 405 | "-----END RSA PUBLIC KEY-----"); |
| 406 | serverPublicKeysFingerprints.push_back(0xbc35f3509f7b7a5LL); |
| 407 |
| 408 | serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" |
| 409 | "MIIBCgKCAQEAvfLHfYH2r9R70w8prHblWt/nDkh+XkgpflqQVcnAfSuTtO05lNPs\n" |
| 410 | "pQmL8Y2XjVT4t8cT6xAkdgfmmvnvRPOOKPi0OfJXoRVylFzAQG/j83u5K3kRLbae\n" |
| 411 | "7fLccVhKZhY46lvsueI1hQdLgNV9n1cQ3TDS2pQOCtovG4eDl9wacrXOJTG2990V\n" |
| 412 | "jgnIKNA0UMoP+KF03qzryqIt3oTvZq03DyWdGK+AZjgBLaDKSnC6qD2cFY81UryR\n" |
| 413 | "WOab8zKkWAnhw2kFpcqhI0jdV5QaSCExvnsjVaX0Y1N0870931/5Jb9ICe4nweZ9\n" |
| 414 | "kSDF/gip3kWLG0o8XQpChDfyvsqB9OLV/wIDAQAB\n" |
| 415 | "-----END RSA PUBLIC KEY-----"); |
| 416 | serverPublicKeysFingerprints.push_back(0x15ae5fa8b5529542LL); |
| 417 |
| 418 | serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" |
| 419 | "MIIBCgKCAQEAs/ditzm+mPND6xkhzwFIz6J/968CtkcSE/7Z2qAJiXbmZ3UDJPGr\n" |
| 420 | "zqTDHkO30R8VeRM/Kz2f4nR05GIFiITl4bEjvpy7xqRDspJcCFIOcyXm8abVDhF+\n" |
| 421 | "th6knSU0yLtNKuQVP6voMrnt9MV1X92LGZQLgdHZbPQz0Z5qIpaKhdyA8DEvWWvS\n" |
| 422 | "Uwwc+yi1/gGaybwlzZwqXYoPOhwMebzKUk0xW14htcJrRrq+PXXQbRzTMynseCoP\n" |
| 423 | "Ioke0dtCodbA3qQxQovE16q9zz4Otv2k4j63cz53J+mhkVWAeWxVGI0lltJmWtEY\n" |
| 424 | "K6er8VqqWot3nqmWMXogrgRLggv/NbbooQIDAQAB\n" |
| 425 | "-----END RSA PUBLIC KEY-----"); |
| 426 | serverPublicKeysFingerprints.push_back(0xaeae98e13cd7f94fLL); |
| 427 |
| 428 | serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" |
| 429 | "MIIBCgKCAQEAvmpxVY7ld/8DAjz6F6q05shjg8/4p6047bn6/m8yPy1RBsvIyvuD\n" |
| 430 | "uGnP/RzPEhzXQ9UJ5Ynmh2XJZgHoE9xbnfxL5BXHplJhMtADXKM9bWB11PU1Eioc\n" |
| 431 | "3+AXBB8QiNFBn2XI5UkO5hPhbb9mJpjA9Uhw8EdfqJP8QetVsI/xrCEbwEXe0xvi\n" |
| 432 | "fRLJbY08/Gp66KpQvy7g8w7VB8wlgePexW3pT13Ap6vuC+mQuJPyiHvSxjEKHgqe\n" |
| 433 | "Pji9NP3tJUFQjcECqcm0yV7/2d0t/pbCm+ZH1sadZspQCEPPrtbkQBlvHb4OLiIW\n" |
| 434 | "PGHKSMeRFvp3IWcmdJqXahxLCUS1Eh6MAQIDAQAB\n" |
| 435 | "-----END RSA PUBLIC KEY-----"); |
| 436 | serverPublicKeysFingerprints.push_back(0x5a181b2235057d98LL); |
| 437 | } |
| 438 |
| 439 | size_t count2 = serverPublicKeysFingerprints.size(); |
| 440 | for (uint32_t a = 0; a < count1; a++) { |
| 441 | for (uint32_t b = 0; b < count2; b++) { |
| 442 | if ((uint64_t) result->server_public_key_fingerprints[a] == serverPublicKeysFingerprints[b]) { |
| 443 | keyFingerprint = result->server_public_key_fingerprints[a]; |
| 444 | key = serverPublicKeys[a]; |
| 445 | break; |
| 446 | } |
| 447 | } |
| 448 | if (keyFingerprint != 0) { |
| 449 | break; |
| 450 | } |
| 451 | } |
| 452 | } |
| 453 |
| 454 | if (keyFingerprint == 0) { |
| 455 | if (currentDatacenter->isCdnDatacenter) { |
| 456 | if (LOGS_ENABLED) DEBUG_D("dc%u handshake: can't find valid cdn server public key, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 457 | loadCdnConfig(currentDatacenter); |
| 458 | } else { |
| 459 | if (LOGS_ENABLED) DEBUG_E("dc%u handshake: can't find valid server public key, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 460 | beginHandshake(false); |
| 461 | } |
| 462 | return; |
| 463 | } |
| 464 |
| 465 | authServerNonce = new ByteArray(result->server_nonce.get()); |
| 466 |
| 467 | uint64_t pq = ((uint64_t) (result->pq->bytes[0] & 0xff) << 56) | |
| 468 | ((uint64_t) (result->pq->bytes[1] & 0xff) << 48) | |
| 469 | ((uint64_t) (result->pq->bytes[2] & 0xff) << 40) | |
| 470 | ((uint64_t) (result->pq->bytes[3] & 0xff) << 32) | |
| 471 | ((uint64_t) (result->pq->bytes[4] & 0xff) << 24) | |
| 472 | ((uint64_t) (result->pq->bytes[5] & 0xff) << 16) | |
| 473 | ((uint64_t) (result->pq->bytes[6] & 0xff) << 8) | |
| 474 | ((uint64_t) (result->pq->bytes[7] & 0xff)); |
| 475 | uint32_t p, q; |
| 476 | if (!factorizeValue(pq, p, q)) { |
| 477 | beginHandshake(false); |
| 478 | return; |
| 479 | } |
| 480 |
| 481 | TL_req_DH_params *request = new TL_req_DH_params(); |
| 482 | request->nonce = std::unique_ptr<ByteArray>(new ByteArray(authNonce)); |
| 483 | request->server_nonce = std::unique_ptr<ByteArray>(new ByteArray(authServerNonce)); |
| 484 | request->p = std::unique_ptr<ByteArray>(new ByteArray(4)); |
| 485 | request->p->bytes[3] = (uint8_t) p; |
| 486 | request->p->bytes[2] = (uint8_t) (p >> 8); |
| 487 | request->p->bytes[1] = (uint8_t) (p >> 16); |
| 488 | request->p->bytes[0] = (uint8_t) (p >> 24); |
| 489 | request->q = std::unique_ptr<ByteArray>(new ByteArray(4)); |
| 490 | request->q->bytes[3] = (uint8_t) q; |
| 491 | request->q->bytes[2] = (uint8_t) (q >> 8); |
| 492 | request->q->bytes[1] = (uint8_t) (q >> 16); |
| 493 | request->q->bytes[0] = (uint8_t) (q >> 24); |
| 494 | request->public_key_fingerprint = keyFingerprint; |
| 495 |
| 496 | TLObject *innerData; |
| 497 | if (handshakeType == HandshakeTypePerm) { |
| 498 | TL_p_q_inner_data_dc *tl_p_q_inner_data = new TL_p_q_inner_data_dc(); |
| 499 | tl_p_q_inner_data->nonce = std::unique_ptr<ByteArray>(new ByteArray(authNonce)); |
| 500 | tl_p_q_inner_data->server_nonce = std::unique_ptr<ByteArray>(new ByteArray(authServerNonce)); |
| 501 | tl_p_q_inner_data->pq = std::unique_ptr<ByteArray>(new ByteArray(result->pq.get())); |
| 502 | tl_p_q_inner_data->p = std::unique_ptr<ByteArray>(new ByteArray(request->p.get())); |
| 503 | tl_p_q_inner_data->q = std::unique_ptr<ByteArray>(new ByteArray(request->q.get())); |
| 504 | tl_p_q_inner_data->new_nonce = std::unique_ptr<ByteArray>(new ByteArray(32)); |
| 505 | if (ConnectionsManager::getInstance(currentDatacenter->instanceNum).testBackend) { |
| 506 | tl_p_q_inner_data->dc = 10000 + currentDatacenter->datacenterId; |
| 507 | } else { |
| 508 | tl_p_q_inner_data->dc = currentDatacenter->datacenterId; |
| 509 | } |
| 510 | RAND_bytes(tl_p_q_inner_data->new_nonce->bytes, 32); |
| 511 | authNewNonce = new ByteArray(tl_p_q_inner_data->new_nonce.get()); |
| 512 | innerData = tl_p_q_inner_data; |
| 513 | } else { |
| 514 | TL_p_q_inner_data_temp_dc *tl_p_q_inner_data_temp = new TL_p_q_inner_data_temp_dc(); |
| 515 | tl_p_q_inner_data_temp->nonce = std::unique_ptr<ByteArray>(new ByteArray(authNonce)); |
| 516 | tl_p_q_inner_data_temp->server_nonce = std::unique_ptr<ByteArray>(new ByteArray(authServerNonce)); |
| 517 | tl_p_q_inner_data_temp->pq = std::unique_ptr<ByteArray>(new ByteArray(result->pq.get())); |
| 518 | tl_p_q_inner_data_temp->p = std::unique_ptr<ByteArray>(new ByteArray(request->p.get())); |
| 519 | tl_p_q_inner_data_temp->q = std::unique_ptr<ByteArray>(new ByteArray(request->q.get())); |
| 520 | tl_p_q_inner_data_temp->new_nonce = std::unique_ptr<ByteArray>(new ByteArray(32)); |
| 521 | /*if (handshakeType == HandshakeTypeMediaTemp) { |
| 522 | if (ConnectionsManager::getInstance(currentDatacenter->instanceNum).testBackend) { |
| 523 | tl_p_q_inner_data_temp->dc = -(10000 + currentDatacenter->datacenterId); |
| 524 | } else { |
| 525 | tl_p_q_inner_data_temp->dc = -currentDatacenter->datacenterId; |
| 526 | } |
| 527 | } else {*/ |
| 528 | if (ConnectionsManager::getInstance(currentDatacenter->instanceNum).testBackend) { |
| 529 | tl_p_q_inner_data_temp->dc = 10000 + currentDatacenter->datacenterId; |
| 530 | } else { |
| 531 | tl_p_q_inner_data_temp->dc = currentDatacenter->datacenterId; |
| 532 | } |
| 533 | //} |
| 534 | tl_p_q_inner_data_temp->expires_in = TEMP_AUTH_KEY_EXPIRE_TIME; |
| 535 | RAND_bytes(tl_p_q_inner_data_temp->new_nonce->bytes, 32); |
| 536 | authNewNonce = new ByteArray(tl_p_q_inner_data_temp->new_nonce.get()); |
| 537 | innerData = tl_p_q_inner_data_temp; |
| 538 | } |
| 539 |
| 540 | uint32_t innerDataSize = innerData->getObjectSize(); |
| 541 | uint32_t additionalSize = innerDataSize + SHA_DIGEST_LENGTH < 255 ? 255 - (innerDataSize + SHA_DIGEST_LENGTH) : 0; |
| 542 | NativeByteBuffer *innerDataBuffer = BuffersStorage::getInstance().getFreeBuffer(innerDataSize + additionalSize + SHA_DIGEST_LENGTH); |
| 543 | innerDataBuffer->position(SHA_DIGEST_LENGTH); |
| 544 | innerData->serializeToStream(innerDataBuffer); |
| 545 | delete innerData; |
| 546 |
| 547 | SHA1(innerDataBuffer->bytes() + SHA_DIGEST_LENGTH, innerDataSize, innerDataBuffer->bytes()); |
| 548 | if (additionalSize != 0) { |
| 549 | RAND_bytes(innerDataBuffer->bytes() + SHA_DIGEST_LENGTH + innerDataSize, additionalSize); |
| 550 | } |
| 551 |
| 552 | BIO *keyBio = BIO_new(BIO_s_mem()); |
| 553 | BIO_write(keyBio, key.c_str(), (int) key.length()); |
| 554 | RSA *rsaKey = PEM_read_bio_RSAPublicKey(keyBio, NULL, NULL, NULL); |
| 555 | BIO_free(keyBio); |
| 556 | if (bnContext == nullptr) { |
| 557 | bnContext = BN_CTX_new(); |
| 558 | } |
| 559 | BIGNUM *a = BN_bin2bn(innerDataBuffer->bytes(), innerDataBuffer->limit(), NULL); |
| 560 | BIGNUM *r = BN_new(); |
| 561 | BN_mod_exp(r, a, rsaKey->e, rsaKey->n, bnContext); |
| 562 | uint32_t size = BN_num_bytes(r); |
| 563 | ByteArray *rsaEncryptedData = new ByteArray(size >= 256 ? size : 256); |
| 564 | size_t resLen = BN_bn2bin(r, rsaEncryptedData->bytes); |
| 565 | if (256 - resLen > 0) { |
| 566 | memset(rsaEncryptedData->bytes + resLen, 0, 256 - resLen); |
| 567 | } |
| 568 | BN_free(a); |
| 569 | BN_free(r); |
| 570 | RSA_free(rsaKey); |
| 571 | innerDataBuffer->reuse(); |
| 572 |
| 573 | request->encrypted_data = std::unique_ptr<ByteArray>(rsaEncryptedData); |
| 574 |
| 575 | sendAckRequest(messageId); |
| 576 | sendRequestData(request, true); |
| 577 | } else { |
| 578 | if (LOGS_ENABLED) DEBUG_E("dc%u handshake: invalid client nonce, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 579 | beginHandshake(false); |
| 580 | } |
| 581 | } else if (dynamic_cast<Server_DH_Params *>(message)) { |
| 582 | if (typeInfo == typeid(TL_server_DH_params_ok)) { |
| 583 | if (handshakeState != 2) { |
| 584 | sendAckRequest(messageId); |
| 585 | return; |
| 586 | } |
| 587 |
| 588 | handshakeState = 3; |
| 589 |
| 590 | TL_server_DH_params_ok *result = (TL_server_DH_params_ok *) message; |
| 591 |
| 592 | NativeByteBuffer *tmpAesKeyAndIv = BuffersStorage::getInstance().getFreeBuffer(84); |
| 593 |
| 594 | NativeByteBuffer *newNonceAndServerNonce = BuffersStorage::getInstance().getFreeBuffer(authNewNonce->length + authServerNonce->length); |
| 595 | newNonceAndServerNonce->writeBytes(authNewNonce); |
| 596 | newNonceAndServerNonce->writeBytes(authServerNonce); |
| 597 | SHA1(newNonceAndServerNonce->bytes(), newNonceAndServerNonce->limit(), tmpAesKeyAndIv->bytes()); |
| 598 | newNonceAndServerNonce->reuse(); |
| 599 |
| 600 | NativeByteBuffer *serverNonceAndNewNonce = BuffersStorage::getInstance().getFreeBuffer(authServerNonce->length + authNewNonce->length); |
| 601 | serverNonceAndNewNonce->writeBytes(authServerNonce); |
| 602 | serverNonceAndNewNonce->writeBytes(authNewNonce); |
| 603 | SHA1(serverNonceAndNewNonce->bytes(), serverNonceAndNewNonce->limit(), tmpAesKeyAndIv->bytes() + 20); |
| 604 | serverNonceAndNewNonce->reuse(); |
| 605 |
| 606 | NativeByteBuffer *newNonceAndNewNonce = BuffersStorage::getInstance().getFreeBuffer(authNewNonce->length + authNewNonce->length); |
| 607 | newNonceAndNewNonce->writeBytes(authNewNonce); |
| 608 | newNonceAndNewNonce->writeBytes(authNewNonce); |
| 609 | SHA1(newNonceAndNewNonce->bytes(), newNonceAndNewNonce->limit(), tmpAesKeyAndIv->bytes() + 40); |
| 610 | newNonceAndNewNonce->reuse(); |
| 611 |
| 612 | memcpy(tmpAesKeyAndIv->bytes() + 60, authNewNonce->bytes, 4); |
| 613 | Datacenter::aesIgeEncryption(result->encrypted_answer->bytes, tmpAesKeyAndIv->bytes(), tmpAesKeyAndIv->bytes() + 32, false, false, result->encrypted_answer->length); |
| 614 |
| 615 | bool hashVerified = false; |
| 616 | for (uint32_t i = 0; i < 16; i++) { |
| 617 | SHA1(result->encrypted_answer->bytes + SHA_DIGEST_LENGTH, result->encrypted_answer->length - i - SHA_DIGEST_LENGTH, tmpAesKeyAndIv->bytes() + 64); |
| 618 | if (!memcmp(tmpAesKeyAndIv->bytes() + 64, result->encrypted_answer->bytes, SHA_DIGEST_LENGTH)) { |
| 619 | hashVerified = true; |
| 620 | break; |
| 621 | } |
| 622 | } |
| 623 |
| 624 | if (!hashVerified) { |
| 625 | if (LOGS_ENABLED) DEBUG_E("dc%u handshake: can't decode DH params, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 626 | beginHandshake(false); |
| 627 | return; |
| 628 | } |
| 629 |
| 630 | bool error = false; |
| 631 | NativeByteBuffer *answerWithHash = new NativeByteBuffer(result->encrypted_answer->bytes + SHA_DIGEST_LENGTH, result->encrypted_answer->length - SHA_DIGEST_LENGTH); |
| 632 | uint32_t constructor = answerWithHash->readUint32(&error); |
| 633 | TL_server_DH_inner_data *dhInnerData = TL_server_DH_inner_data::TLdeserialize(answerWithHash, constructor, currentDatacenter->instanceNum, error); |
| 634 | delete answerWithHash; |
| 635 |
| 636 | if (error) { |
| 637 | if (LOGS_ENABLED) DEBUG_E("dc%u handshake: can't parse decoded DH params, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 638 | beginHandshake(false); |
| 639 | return; |
| 640 | } |
| 641 |
| 642 | if (!authNonce->isEqualTo(dhInnerData->nonce.get())) { |
| 643 | if (LOGS_ENABLED) DEBUG_E("dc%u handshake: invalid DH nonce, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 644 | beginHandshake(false); |
| 645 | return; |
| 646 | } |
| 647 |
| 648 | if (!authServerNonce->isEqualTo(dhInnerData->server_nonce.get())) { |
| 649 | if (LOGS_ENABLED) DEBUG_E("dc%u handshake: invalid DH server nonce, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 650 | beginHandshake(false); |
| 651 | return; |
| 652 | } |
| 653 |
| 654 | BIGNUM *p = BN_bin2bn(dhInnerData->dh_prime->bytes, dhInnerData->dh_prime->length, NULL); |
| 655 | if (p == nullptr) { |
| 656 | if (LOGS_ENABLED) DEBUG_E("can't allocate BIGNUM p"); |
| 657 | exit(1); |
| 658 | } |
| 659 | if (!isGoodPrime(p, dhInnerData->g)) { |
| 660 | if (LOGS_ENABLED) DEBUG_E("dc%u handshake: bad prime, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 661 | beginHandshake(false); |
| 662 | BN_free(p); |
| 663 | return; |
| 664 | } |
| 665 |
| 666 | BIGNUM *g_a = BN_new(); |
| 667 | if (g_a == nullptr) { |
| 668 | if (LOGS_ENABLED) DEBUG_E("can't allocate BIGNUM g_a"); |
| 669 | exit(1); |
| 670 | } |
| 671 | BN_bin2bn(dhInnerData->g_a->bytes, dhInnerData->g_a->length, g_a); |
| 672 | if (!isGoodGaAndGb(g_a, p)) { |
| 673 | if (LOGS_ENABLED) DEBUG_E("dc%u handshake: bad prime and g_a, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 674 | beginHandshake(false); |
| 675 | BN_free(p); |
| 676 | BN_free(g_a); |
| 677 | return; |
| 678 | } |
| 679 |
| 680 | BIGNUM *g = BN_new(); |
| 681 | if (g == nullptr) { |
| 682 | if (LOGS_ENABLED) DEBUG_E("can't allocate BIGNUM g"); |
| 683 | exit(1); |
| 684 | } |
| 685 | if (!BN_set_word(g, dhInnerData->g)) { |
| 686 | if (LOGS_ENABLED) DEBUG_E("OpenSSL error at BN_set_word(g_b, dhInnerData->g)"); |
| 687 | beginHandshake(false); |
| 688 | BN_free(g); |
| 689 | BN_free(g_a); |
| 690 | BN_free(p); |
| 691 | return; |
| 692 | } |
| 693 | thread_local static uint8_t bytes[256]; |
| 694 | RAND_bytes(bytes, 256); |
| 695 | BIGNUM *b = BN_bin2bn(bytes, 256, NULL); |
| 696 | if (b == nullptr) { |
| 697 | if (LOGS_ENABLED) DEBUG_E("can't allocate BIGNUM b"); |
| 698 | exit(1); |
| 699 | } |
| 700 |
| 701 | BIGNUM *g_b = BN_new(); |
| 702 | if (!BN_mod_exp(g_b, g, b, p, bnContext)) { |
| 703 | if (LOGS_ENABLED) DEBUG_E("OpenSSL error at BN_mod_exp(g_b, g, b, p, bnContext)"); |
| 704 | beginHandshake(false); |
| 705 | BN_free(g); |
| 706 | BN_free(g_a); |
| 707 | BN_free(g_b); |
| 708 | BN_free(b); |
| 709 | BN_free(p); |
| 710 | return; |
| 711 | } |
| 712 |
| 713 | TL_client_DH_inner_data *clientInnerData = new TL_client_DH_inner_data(); |
| 714 | clientInnerData->g_b = std::unique_ptr<ByteArray>(new ByteArray(BN_num_bytes(g_b))); |
| 715 | BN_bn2bin(g_b, clientInnerData->g_b->bytes); |
| 716 | clientInnerData->nonce = std::unique_ptr<ByteArray>(new ByteArray(authNonce)); |
| 717 | clientInnerData->server_nonce = std::unique_ptr<ByteArray>(new ByteArray(authServerNonce)); |
| 718 | clientInnerData->retry_id = 0; |
| 719 | BN_free(g_b); |
| 720 | BN_free(g); |
| 721 |
| 722 | BIGNUM *authKeyNum = BN_new(); |
| 723 | BN_mod_exp(authKeyNum, g_a, b, p, bnContext); |
| 724 | size_t l = BN_num_bytes(authKeyNum); |
| 725 | handshakeAuthKey = new ByteArray(256); |
| 726 | BN_bn2bin(authKeyNum, handshakeAuthKey->bytes); |
| 727 | if (l < 256) { |
| 728 | memmove(handshakeAuthKey->bytes + 256 - l, handshakeAuthKey->bytes, l); |
| 729 | memset(handshakeAuthKey->bytes, 0, 256 - l); |
| 730 | } |
| 731 |
| 732 | BN_free(authKeyNum); |
| 733 | BN_free(g_a); |
| 734 | BN_free(b); |
| 735 | BN_free(p); |
| 736 |
| 737 | uint32_t clientInnerDataSize = clientInnerData->getObjectSize(); |
| 738 | uint32_t additionalSize = (clientInnerDataSize + SHA_DIGEST_LENGTH) % 16; |
| 739 | if (additionalSize != 0) { |
| 740 | additionalSize = 16 - additionalSize; |
| 741 | } |
| 742 | NativeByteBuffer *clientInnerDataBuffer = BuffersStorage::getInstance().getFreeBuffer(clientInnerDataSize + additionalSize + SHA_DIGEST_LENGTH); |
| 743 | clientInnerDataBuffer->position(SHA_DIGEST_LENGTH); |
| 744 | clientInnerData->serializeToStream(clientInnerDataBuffer); |
| 745 | delete clientInnerData; |
| 746 |
| 747 | SHA1(clientInnerDataBuffer->bytes() + SHA_DIGEST_LENGTH, clientInnerDataSize, clientInnerDataBuffer->bytes()); |
| 748 |
| 749 | if (additionalSize != 0) { |
| 750 | RAND_bytes(clientInnerDataBuffer->bytes() + SHA_DIGEST_LENGTH + clientInnerDataSize, additionalSize); |
| 751 | } |
| 752 |
| 753 | TL_set_client_DH_params *setClientDhParams = new TL_set_client_DH_params(); |
| 754 | setClientDhParams->nonce = std::unique_ptr<ByteArray>(new ByteArray(authNonce)); |
| 755 | setClientDhParams->server_nonce = std::unique_ptr<ByteArray>(new ByteArray(authServerNonce)); |
| 756 | Datacenter::aesIgeEncryption(clientInnerDataBuffer->bytes(), tmpAesKeyAndIv->bytes(), tmpAesKeyAndIv->bytes() + 32, true, false, clientInnerDataBuffer->limit()); |
| 757 | setClientDhParams->encrypted_data = std::unique_ptr<ByteArray>(new ByteArray(clientInnerDataBuffer->bytes(), clientInnerDataBuffer->limit())); |
| 758 | clientInnerDataBuffer->reuse(); |
| 759 | tmpAesKeyAndIv->reuse(); |
| 760 |
| 761 | sendAckRequest(messageId); |
| 762 | sendRequestData(setClientDhParams, true); |
| 763 |
| 764 | int32_t currentTime = (int32_t) (ConnectionsManager::getInstance(currentDatacenter->instanceNum).getCurrentTimeMillis() / 1000); |
| 765 | timeDifference = dhInnerData->server_time - currentTime; |
| 766 |
| 767 | handshakeServerSalt = new TL_future_salt(); |
| 768 | handshakeServerSalt->valid_since = currentTime + timeDifference - 5; |
| 769 | handshakeServerSalt->valid_until = handshakeServerSalt->valid_since + 30 * 60; |
| 770 | for (int32_t a = 7; a >= 0; a--) { |
| 771 | handshakeServerSalt->salt <<= 8; |
| 772 | handshakeServerSalt->salt |= (authNewNonce->bytes[a] ^ authServerNonce->bytes[a]); |
| 773 | } |
| 774 | } else { |
| 775 | if (LOGS_ENABLED) DEBUG_E("dc%u handshake: can't set DH params, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 776 | beginHandshake(false); |
| 777 | } |
| 778 | } else if (dynamic_cast<Set_client_DH_params_answer *>(message)) { |
| 779 | if (handshakeState != 3) { |
| 780 | sendAckRequest(messageId); |
| 781 | return; |
| 782 | } |
| 783 |
| 784 | handshakeState = 4; |
| 785 |
| 786 | Set_client_DH_params_answer *result = (Set_client_DH_params_answer *) message; |
| 787 |
| 788 | if (!authNonce->isEqualTo(result->nonce.get())) { |
| 789 | if (LOGS_ENABLED) DEBUG_E("dc%u handshake: invalid DH answer nonce, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 790 | beginHandshake(false); |
| 791 | return; |
| 792 | } |
| 793 | if (!authServerNonce->isEqualTo(result->server_nonce.get())) { |
| 794 | if (LOGS_ENABLED) DEBUG_E("dc%u handshake: invalid DH answer server nonce, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 795 | beginHandshake(false); |
| 796 | return; |
| 797 | } |
| 798 |
| 799 | sendAckRequest(messageId); |
| 800 |
| 801 | uint32_t authKeyAuxHashLength = authNewNonce->length + SHA_DIGEST_LENGTH + 1; |
| 802 | NativeByteBuffer *authKeyAuxHashBuffer = BuffersStorage::getInstance().getFreeBuffer(authKeyAuxHashLength + SHA_DIGEST_LENGTH); |
| 803 | authKeyAuxHashBuffer->writeBytes(authNewNonce); |
| 804 | SHA1(handshakeAuthKey->bytes, handshakeAuthKey->length, authKeyAuxHashBuffer->bytes() + authNewNonce->length + 1); |
| 805 |
| 806 | if (typeInfo == typeid(TL_dh_gen_ok)) { |
| 807 | authKeyAuxHashBuffer->writeByte(1); |
| 808 | SHA1(authKeyAuxHashBuffer->bytes(), authKeyAuxHashLength - 12, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength); |
| 809 |
| 810 | if (memcmp(result->new_nonce_hash1->bytes, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength + SHA_DIGEST_LENGTH - 16, 16)) { |
| 811 | if (LOGS_ENABLED) DEBUG_E("dc%u handshake: invalid DH answer nonce hash 1, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 812 | authKeyAuxHashBuffer->reuse(); |
| 813 | beginHandshake(false); |
| 814 | } else { |
| 815 | if (LOGS_ENABLED) DEBUG_D("dc%u handshake: completed, time difference = %d, type = %d", currentDatacenter->datacenterId, timeDifference, handshakeType); |
| 816 | authKeyAuxHashBuffer->position(authNewNonce->length + 1 + 12); |
| 817 | authKeyTempPendingId = authKeyAuxHashBuffer->readInt64(nullptr); |
| 818 | authKeyAuxHashBuffer->reuse(); |
| 819 |
| 820 | if (handshakeRequest != nullptr) { |
| 821 | delete handshakeRequest; |
| 822 | handshakeRequest = nullptr; |
| 823 | } |
| 824 |
| 825 | std::unique_ptr<TL_future_salt> salt = std::unique_ptr<TL_future_salt>(handshakeServerSalt); |
| 826 | currentDatacenter->addServerSalt(salt); |
| 827 | handshakeServerSalt = nullptr; |
| 828 |
| 829 | if (handshakeType == HandshakeTypePerm) { |
| 830 | ConnectionsManager::getInstance(currentDatacenter->instanceNum).scheduleTask([&] { |
| 831 | ByteArray *authKey = handshakeAuthKey; |
| 832 | handshakeAuthKey = nullptr; |
| 833 | delegate->onHandshakeComplete(this, authKeyTempPendingId, authKey, timeDifference); |
| 834 | }); |
| 835 | } else { |
| 836 | authKeyTempPending = handshakeAuthKey; |
| 837 | handshakeAuthKey = nullptr; |
| 838 |
| 839 | Connection *connection = getConnection(); |
| 840 |
| 841 | TL_auth_bindTempAuthKey *request = new TL_auth_bindTempAuthKey(); |
| 842 | request->initFunc = [&, request, connection](int64_t messageId) { |
| 843 | TL_bind_auth_key_inner *inner = new TL_bind_auth_key_inner(); |
| 844 | inner->expires_at = ConnectionsManager::getInstance(currentDatacenter->instanceNum).getCurrentTime() + timeDifference + TEMP_AUTH_KEY_EXPIRE_TIME; |
| 845 | inner->perm_auth_key_id = currentDatacenter->authKeyPermId; |
| 846 | inner->temp_auth_key_id = authKeyTempPendingId; |
| 847 | RAND_bytes((uint8_t *) &inner->nonce, 8); |
| 848 | inner->temp_session_id = connection->getSessionId(); |
| 849 |
| 850 | NetworkMessage *networkMessage = new NetworkMessage(); |
| 851 | networkMessage->message = std::unique_ptr<TL_message>(new TL_message()); |
| 852 | networkMessage->message->msg_id = authKeyPendingMessageId = messageId; |
| 853 | networkMessage->message->bytes = inner->getObjectSize(); |
| 854 | networkMessage->message->body = std::unique_ptr<TLObject>(inner); |
| 855 | networkMessage->message->seqno = 0; |
| 856 |
| 857 | std::vector<std::unique_ptr<NetworkMessage>> array; |
| 858 | array.push_back(std::unique_ptr<NetworkMessage>(networkMessage)); |
| 859 |
| 860 | request->perm_auth_key_id = inner->perm_auth_key_id; |
| 861 | request->nonce = inner->nonce; |
| 862 | request->expires_at = inner->expires_at; |
| 863 | request->encrypted_message = currentDatacenter->createRequestsData(array, nullptr, connection, true); |
| 864 | }; |
| 865 |
| 866 | authKeyPendingRequestId = ConnectionsManager::getInstance(currentDatacenter->instanceNum).sendRequest(request, [&](TLObject *response, TL_error *error, int32_t networkType) { |
| 867 | authKeyPendingMessageId = 0; |
| 868 | authKeyPendingRequestId = 0; |
| 869 | if (response != nullptr && typeid(*response) == typeid(TL_boolTrue)) { |
| 870 | if (LOGS_ENABLED) DEBUG_D("dc%u handshake: bind completed", currentDatacenter->datacenterId); |
| 871 | ConnectionsManager::getInstance(currentDatacenter->instanceNum).scheduleTask([&] { |
| 872 | ByteArray *authKey = authKeyTempPending; |
| 873 | authKeyTempPending = nullptr; |
| 874 | delegate->onHandshakeComplete(this, authKeyTempPendingId, authKey, timeDifference); |
| 875 | }); |
| 876 | } else { |
| 877 | ConnectionsManager::getInstance(currentDatacenter->instanceNum).scheduleTask([&] { |
| 878 | beginHandshake(true); |
| 879 | }); |
| 880 | } |
| 881 | }, nullptr, RequestFlagWithoutLogin | RequestFlagEnableUnauthorized | RequestFlagUseUnboundKey, currentDatacenter->datacenterId, connection->getConnectionType(), true, 0); |
| 882 | } |
| 883 | } |
| 884 | } else if (typeInfo == typeid(TL_dh_gen_retry)) { |
| 885 | authKeyAuxHashBuffer->writeByte(2); |
| 886 | SHA1(authKeyAuxHashBuffer->bytes(), authKeyAuxHashLength - 12, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength); |
| 887 |
| 888 | if (memcmp(result->new_nonce_hash2->bytes, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength + SHA_DIGEST_LENGTH - 16, 16)) { |
| 889 | if (LOGS_ENABLED) DEBUG_E("dc%u handshake: invalid DH answer nonce hash 2, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 890 | beginHandshake(false); |
| 891 | } else { |
| 892 | if (LOGS_ENABLED) DEBUG_D("dc%u handshake: retry DH, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 893 | beginHandshake(false); |
| 894 | } |
| 895 | authKeyAuxHashBuffer->reuse(); |
| 896 | } else if (typeInfo == typeid(TL_dh_gen_fail)) { |
| 897 | authKeyAuxHashBuffer->writeByte(3); |
| 898 | SHA1(authKeyAuxHashBuffer->bytes(), authKeyAuxHashLength - 12, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength); |
| 899 |
| 900 | if (memcmp(result->new_nonce_hash3->bytes, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength + SHA_DIGEST_LENGTH - 16, 16)) { |
| 901 | if (LOGS_ENABLED) DEBUG_E("dc%u handshake: invalid DH answer nonce hash 3, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 902 | beginHandshake(false); |
| 903 | } else { |
| 904 | if (LOGS_ENABLED) DEBUG_E("dc%u handshake: server declined DH params, type = %d", currentDatacenter->datacenterId, handshakeType); |
| 905 | beginHandshake(false); |
| 906 | } |
| 907 | authKeyAuxHashBuffer->reuse(); |
| 908 | } |
| 909 | } |
| 910 | } |
| 911 |
| 912 | void Handshake::sendAckRequest(int64_t messageId) { |
| 913 | TL_msgs_ack *msgsAck = new TL_msgs_ack(); |
| 914 | msgsAck->msg_ids.push_back(messageId); |
| 915 | sendRequestData(msgsAck, false); |
| 916 | } |
| 917 |
| 918 | TLObject *Handshake::getCurrentHandshakeRequest() { |
| 919 | return handshakeRequest; |
| 920 | } |
| 921 |
| 922 | void Handshake::saveCdnConfigInternal(NativeByteBuffer *buffer) { |
| 923 | buffer->writeInt32(1); |
| 924 | buffer->writeInt32((int32_t) cdnPublicKeys.size()); |
| 925 | for (std::map<int32_t, std::string>::iterator iter = cdnPublicKeys.begin(); iter != cdnPublicKeys.end(); iter++) { |
| 926 | buffer->writeInt32(iter->first); |
| 927 | buffer->writeString(iter->second); |
| 928 | buffer->writeInt64(cdnPublicKeysFingerprints[iter->first]); |
| 929 | } |
| 930 | } |
| 931 |
| 932 | void Handshake::saveCdnConfig(Datacenter *datacenter) { |
| 933 | if (cdnConfig == nullptr) { |
| 934 | cdnConfig = new Config(datacenter->instanceNum, "cdnkeys.dat"); |
| 935 | } |
| 936 | thread_local static NativeByteBuffer *sizeCalculator = new NativeByteBuffer(true); |
| 937 | sizeCalculator->clearCapacity(); |
| 938 | saveCdnConfigInternal(sizeCalculator); |
| 939 | NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(sizeCalculator->capacity()); |
| 940 | saveCdnConfigInternal(buffer); |
| 941 | cdnConfig->writeConfig(buffer); |
| 942 | buffer->reuse(); |
| 943 | } |
| 944 |
| 945 | void Handshake::loadCdnConfig(Datacenter *datacenter) { |
| 946 | if (std::find(cdnWaitingDatacenters.begin(), cdnWaitingDatacenters.end(), datacenter) != cdnWaitingDatacenters.end()) { |
| 947 | return; |
| 948 | } |
| 949 | cdnWaitingDatacenters.push_back(datacenter); |
| 950 | if (loadingCdnKeys) { |
| 951 | return; |
| 952 | } |
| 953 | if (cdnPublicKeysFingerprints.empty()) { |
| 954 | if (cdnConfig == nullptr) { |
| 955 | cdnConfig = new Config(datacenter->instanceNum, "cdnkeys.dat"); |
| 956 | } |
| 957 | NativeByteBuffer *buffer = cdnConfig->readConfig(); |
| 958 | if (buffer != nullptr) { |
| 959 | uint32_t version = buffer->readUint32(nullptr); |
| 960 | if (version >= 1) { |
| 961 | size_t count = buffer->readUint32(nullptr); |
| 962 | for (uint32_t a = 0; a < count; a++) { |
| 963 | int dcId = buffer->readInt32(nullptr); |
| 964 | cdnPublicKeys[dcId] = buffer->readString(nullptr); |
| 965 | cdnPublicKeysFingerprints[dcId] = buffer->readUint64(nullptr); |
| 966 | } |
| 967 | } |
| 968 | buffer->reuse(); |
| 969 | if (!cdnPublicKeysFingerprints.empty()) { |
| 970 | size_t count = cdnWaitingDatacenters.size(); |
| 971 | for (uint32_t a = 0; a < count; a++) { |
| 972 | cdnWaitingDatacenters[a]->beginHandshake(HandshakeTypeCurrent, false); |
| 973 | } |
| 974 | cdnWaitingDatacenters.clear(); |
| 975 | return; |
| 976 | } |
| 977 | } |
| 978 | } |
| 979 | loadingCdnKeys = true; |
| 980 | TL_help_getCdnConfig *request = new TL_help_getCdnConfig(); |
| 981 |
| 982 | ConnectionsManager::getInstance(datacenter->instanceNum).sendRequest(request, [&, datacenter](TLObject *response, TL_error *error, int32_t networkType) { |
| 983 | if (response != nullptr) { |
| 984 | TL_cdnConfig *config = (TL_cdnConfig *) response; |
| 985 | size_t count = config->public_keys.size(); |
| 986 | BIO *keyBio = BIO_new(BIO_s_mem()); |
| 987 | NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(1024); |
| 988 | thread_local static uint8_t sha1Buffer[20]; |
| 989 | for (uint32_t a = 0; a < count; a++) { |
| 990 | TL_cdnPublicKey *publicKey = config->public_keys[a].get(); |
| 991 | cdnPublicKeys[publicKey->dc_id] = publicKey->public_key; |
| 992 |
| 993 | BIO_write(keyBio, publicKey->public_key.c_str(), (int) publicKey->public_key.length()); |
| 994 | RSA *rsaKey = PEM_read_bio_RSAPublicKey(keyBio, NULL, NULL, NULL); |
| 995 |
| 996 | int nBytes = BN_num_bytes(rsaKey->n); |
| 997 | int eBytes = BN_num_bytes(rsaKey->e); |
| 998 | std::string nStr(nBytes, 0), eStr(eBytes, 0); |
| 999 | BN_bn2bin(rsaKey->n, (uint8_t *)&nStr[0]); |
| 1000 | BN_bn2bin(rsaKey->e, (uint8_t *)&eStr[0]); |
| 1001 | buffer->writeString(nStr); |
| 1002 | buffer->writeString(eStr); |
| 1003 | SHA1(buffer->bytes(), buffer->position(), sha1Buffer); |
| 1004 | cdnPublicKeysFingerprints[publicKey->dc_id] = ((uint64_t) sha1Buffer[19]) << 56 | |
| 1005 | ((uint64_t) sha1Buffer[18]) << 48 | |
| 1006 | ((uint64_t) sha1Buffer[17]) << 40 | |
| 1007 | ((uint64_t) sha1Buffer[16]) << 32 | |
| 1008 | ((uint64_t) sha1Buffer[15]) << 24 | |
| 1009 | ((uint64_t) sha1Buffer[14]) << 16 | |
| 1010 | ((uint64_t) sha1Buffer[13]) << 8 | |
| 1011 | ((uint64_t) sha1Buffer[12]); |
| 1012 | RSA_free(rsaKey); |
| 1013 | if (a != count - 1) { |
| 1014 | buffer->position(0); |
| 1015 | BIO_reset(keyBio); |
| 1016 | } |
| 1017 | } |
| 1018 | buffer->reuse(); |
| 1019 | BIO_free(keyBio); |
| 1020 | count = cdnWaitingDatacenters.size(); |
| 1021 | for (uint32_t a = 0; a < count; a++) { |
| 1022 | cdnWaitingDatacenters[a]->beginHandshake(HandshakeTypeCurrent, false); |
| 1023 | } |
| 1024 | cdnWaitingDatacenters.clear(); |
| 1025 | saveCdnConfig(datacenter); |
| 1026 | } |
| 1027 | loadingCdnKeys = false; |
| 1028 | }, nullptr, RequestFlagEnableUnauthorized | RequestFlagWithoutLogin, DEFAULT_DATACENTER_ID, ConnectionTypeGeneric, true); |
| 1029 | } |
| 1030 |
| 1031 | HandshakeType Handshake::getType() { |
| 1032 | return handshakeType; |
| 1033 | } |
| 1034 |
| 1035 | ByteArray *Handshake::getAuthKeyTempPending() { |
| 1036 | return authKeyTempPending; |
| 1037 | } |
| 1038 |
| 1039 | int64_t Handshake::getAuthKeyTempPendingId() { |
| 1040 | return authKeyTempPendingId; |
| 1041 | } |
| 1042 |
| 1043 | void Handshake::onHandshakeConnectionClosed() { |
| 1044 | if (handshakeState == 0) { |
| 1045 | return; |
| 1046 | } |
| 1047 | needResendData = true; |
| 1048 | } |
| 1049 |
| 1050 | void Handshake::onHandshakeConnectionConnected() { |
| 1051 | if (handshakeState == 0 || !needResendData) { |
| 1052 | return; |
| 1053 | } |
| 1054 | beginHandshake(false); |
| 1055 | } |
| 1056 |