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