| 6 |
| * Copyright Nikolai Kudashov, 2015. |
| 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 "Datacenter.h" |
| 18 | #include "Connection.h" |
| 19 | #include "MTProtoScheme.h" |
| 20 | #include "FileLog.h" |
| 21 | #include "NativeByteBuffer.h" |
| 22 | #include "ByteArray.h" |
| 23 | #include "BuffersStorage.h" |
| 24 | #include "ConnectionsManager.h" |
| 25 | #include "Config.h" |
| 26 |
| 27 | static std::vector<std::string> serverPublicKeys; |
| 28 | static std::vector<uint64_t> serverPublicKeysFingerprints; |
| 29 | static BN_CTX *bnContext; |
| 30 |
| 31 | Datacenter::Datacenter(uint32_t id) { |
| 32 | datacenterId = id; |
| 33 | for (uint32_t a = 0; a < DOWNLOAD_CONNECTIONS_COUNT; a++) { |
| 34 | downloadConnections[a] = nullptr; |
| 35 | } |
| 36 | } |
| 37 |
| 38 | Datacenter::Datacenter(NativeByteBuffer *data) { |
| 39 | for (uint32_t a = 0; a < DOWNLOAD_CONNECTIONS_COUNT; a++) { |
| 40 | downloadConnections[a] = nullptr; |
| 41 | } |
| 42 | uint32_t currentVersion = data->readUint32(nullptr); |
| 43 | if (currentVersion >= 2 && currentVersion <= 5) { |
| 44 | datacenterId = data->readUint32(nullptr); |
| 45 | if (currentVersion >= 3) { |
| 46 | lastInitVersion = data->readUint32(nullptr); |
| 47 | } |
| 48 | uint32_t len = data->readUint32(nullptr); |
| 49 | for (uint32_t a = 0; a < len; a++) { |
| 50 | std::string address = data->readString(nullptr); |
| 51 | addressesIpv4.push_back(address); |
| 52 | ports[address] = data->readUint32(nullptr); |
| 53 | } |
| 54 | if (currentVersion >= 5) { |
| 55 | len = data->readUint32(nullptr); |
| 56 | for (uint32_t a = 0; a < len; a++) { |
| 57 | std::string address = data->readString(nullptr); |
| 58 | addressesIpv6.push_back(address); |
| 59 | ports[address] = data->readUint32(nullptr); |
| 60 | } |
| 61 | len = data->readUint32(nullptr); |
| 62 | for (uint32_t a = 0; a < len; a++) { |
| 63 | std::string address = data->readString(nullptr); |
| 64 | addressesIpv4Download.push_back(address); |
| 65 | ports[address] = data->readUint32(nullptr); |
| 66 | } |
| 67 | len = data->readUint32(nullptr); |
| 68 | for (uint32_t a = 0; a < len; a++) { |
| 69 | std::string address = data->readString(nullptr); |
| 70 | addressesIpv6Download.push_back(address); |
| 71 | ports[address] = data->readUint32(nullptr); |
| 72 | } |
| 73 | } |
| 74 | len = data->readUint32(nullptr); |
| 75 | if (len != 0) { |
| 76 | authKey = data->readBytes(len, nullptr); |
| 77 | } |
| 78 | if (currentVersion >= 4) { |
| 79 | authKeyId = data->readInt64(nullptr); |
| 80 | } else { |
| 81 | len = data->readUint32(nullptr); |
| 82 | if (len != 0) { |
| 83 | authKeyId = data->readInt64(nullptr); |
| 84 | } |
| 85 | } |
| 86 | authorized = data->readInt32(nullptr) != 0; |
| 87 | len = data->readUint32(nullptr); |
| 88 | for (uint32_t a = 0; a < len; a++) { |
| 89 | TL_future_salt *salt = new TL_future_salt(); |
| 90 | salt->valid_since = data->readInt32(nullptr); |
| 91 | salt->valid_until = data->readInt32(nullptr); |
| 92 | salt->salt = data->readInt64(nullptr); |
| 93 | serverSalts.push_back(std::unique_ptr<TL_future_salt>(salt)); |
| 94 | } |
| 95 | } |
| 96 |
| 97 | if (config == nullptr) { |
| 98 | config = new Config("dc" + to_string_int32(datacenterId) + "conf.dat"); |
| 99 | } |
| 100 | NativeByteBuffer *buffer = config->readConfig(); |
| 101 | if (buffer != nullptr) { |
| 102 | uint32_t version = buffer->readUint32(nullptr); |
| 103 | if (version <= paramsConfigVersion) { |
| 104 | currentPortNumIpv4 = buffer->readUint32(nullptr); |
| 105 | currentAddressNumIpv4 = buffer->readUint32(nullptr); |
| 106 | currentPortNumIpv6 = buffer->readUint32(nullptr); |
| 107 | currentAddressNumIpv6 = buffer->readUint32(nullptr); |
| 108 | currentPortNumIpv4Download = buffer->readUint32(nullptr); |
| 109 | currentAddressNumIpv4Download = buffer->readUint32(nullptr); |
| 110 | currentPortNumIpv6Download = buffer->readUint32(nullptr); |
| 111 | currentAddressNumIpv6Download = buffer->readUint32(nullptr); |
| 112 | } |
| 113 | buffer->reuse(); |
| 114 | } else { |
| 115 | currentPortNumIpv4 = 0; |
| 116 | currentAddressNumIpv4 = 0; |
| 117 | currentPortNumIpv6 = 0; |
| 118 | currentAddressNumIpv6 = 0; |
| 119 | currentPortNumIpv4Download = 0; |
| 120 | currentAddressNumIpv4Download = 0; |
| 121 | currentPortNumIpv6Download = 0; |
| 122 | currentAddressNumIpv6Download = 0; |
| 123 | } |
| 124 | } |
| 125 |
| 126 | void Datacenter::switchTo443Port() { |
| 127 | for (uint32_t a = 0; a < addressesIpv4.size(); a++) { |
| 128 | if (ports[addressesIpv4[a]] == 443) { |
| 129 | currentAddressNumIpv4 = a; |
| 130 | currentPortNumIpv4 = 0; |
| 131 | break; |
| 132 | } |
| 133 | } |
| 134 | for (uint32_t a = 0; a < addressesIpv6.size(); a++) { |
| 135 | if (ports[addressesIpv6[a]] == 443) { |
| 136 | currentAddressNumIpv6 = a; |
| 137 | currentPortNumIpv6 = 0; |
| 138 | break; |
| 139 | } |
| 140 | } |
| 141 | for (uint32_t a = 0; a < addressesIpv4Download.size(); a++) { |
| 142 | if (ports[addressesIpv4Download[a]] == 443) { |
| 143 | currentAddressNumIpv4Download = a; |
| 144 | currentPortNumIpv4Download = 0; |
| 145 | break; |
| 146 | } |
| 147 | } |
| 148 | for (uint32_t a = 0; a < addressesIpv6Download.size(); a++) { |
| 149 | if (ports[addressesIpv6Download[a]] == 443) { |
| 150 | currentAddressNumIpv6Download = a; |
| 151 | currentPortNumIpv6Download = 0; |
| 152 | break; |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 |
| 157 | std::string Datacenter::getCurrentAddress(uint32_t flags) { |
| 158 | uint32_t currentAddressNum; |
| 159 | std::vector<std::string> *addresses; |
| 160 | if ((flags & 2) != 0) { |
| 161 | if ((flags & 1) != 0) { |
| 162 | currentAddressNum = currentAddressNumIpv6Download; |
| 163 | addresses = &addressesIpv6Download; |
| 164 | } else { |
| 165 | currentAddressNum = currentAddressNumIpv4Download; |
| 166 | addresses = &addressesIpv4Download; |
| 167 | } |
| 168 | } else { |
| 169 | if ((flags & 1) != 0) { |
| 170 | currentAddressNum = currentAddressNumIpv6; |
| 171 | addresses = &addressesIpv6; |
| 172 | } else { |
| 173 | currentAddressNum = currentAddressNumIpv4; |
| 174 | addresses = &addressesIpv4; |
| 175 | } |
| 176 | } |
| 177 | if (addresses->empty()) { |
| 178 | return std::string(""); |
| 179 | } |
| 180 | if (currentAddressNum >= addresses->size()) { |
| 181 | currentAddressNum = 0; |
| 182 | if ((flags & 2) != 0) { |
| 183 | if ((flags & 1) != 0) { |
| 184 | currentAddressNumIpv6Download = currentAddressNum; |
| 185 | } else { |
| 186 | currentAddressNumIpv4Download = currentAddressNum; |
| 187 | } |
| 188 | } else { |
| 189 | if ((flags & 1) != 0) { |
| 190 | currentAddressNumIpv6 = currentAddressNum; |
| 191 | } else { |
| 192 | currentAddressNumIpv4 = currentAddressNum; |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | return (*addresses)[currentAddressNum]; |
| 197 | } |
| 198 |
| 199 | int32_t Datacenter::getCurrentPort(uint32_t flags) { |
| 200 | if (ports.empty()) { |
| 201 | return overridePort == -1 ? 443 : overridePort; |
| 202 | } |
| 203 |
| 204 | const int32_t *portsArray = overridePort == 8888 ? defaultPorts8888 : defaultPorts; |
| 205 |
| 206 | uint32_t currentPortNum; |
| 207 | if ((flags & 2) != 0) { |
| 208 | if ((flags & 1) != 0) { |
| 209 | currentPortNum = currentPortNumIpv6Download; |
| 210 | } else { |
| 211 | currentPortNum = currentPortNumIpv4Download; |
| 212 | } |
| 213 | } else { |
| 214 | if ((flags & 1) != 0) { |
| 215 | currentPortNum = currentPortNumIpv6; |
| 216 | } else { |
| 217 | currentPortNum = currentPortNumIpv4; |
| 218 | } |
| 219 | } |
| 220 |
| 221 | if (currentPortNum >= 11) { |
| 222 | currentPortNum = 0; |
| 223 | if ((flags & 2) != 0) { |
| 224 | if ((flags & 1) != 0) { |
| 225 | currentPortNumIpv6Download = currentPortNum; |
| 226 | } else { |
| 227 | currentPortNumIpv4Download = currentPortNum; |
| 228 | } |
| 229 | } else { |
| 230 | if ((flags & 1) != 0) { |
| 231 | currentPortNumIpv6 = currentPortNum; |
| 232 | } else { |
| 233 | currentPortNumIpv4 = currentPortNum; |
| 234 | } |
| 235 | } |
| 236 | } |
| 237 | int32_t port = portsArray[currentPortNum]; |
| 238 | if (port == -1) { |
| 239 | if (overridePort != -1) { |
| 240 | return overridePort; |
| 241 | } |
| 242 | std::string address = getCurrentAddress(flags); |
| 243 | return ports[address]; |
| 244 | } |
| 245 | return port; |
| 246 | } |
| 247 |
| 248 | void Datacenter::addAddressAndPort(std::string address, uint32_t port, uint32_t flags) { |
| 249 | std::vector<std::string> *addresses; |
| 250 | if ((flags & 2) != 0) { |
| 251 | if ((flags & 1) != 0) { |
| 252 | addresses = &addressesIpv6Download; |
| 253 | } else { |
| 254 | addresses = &addressesIpv4Download; |
| 255 | } |
| 256 | } else { |
| 257 | if ((flags & 1) != 0) { |
| 258 | addresses = &addressesIpv6; |
| 259 | } else { |
| 260 | addresses = &addressesIpv4; |
| 261 | } |
| 262 | } |
| 263 | if (std::find(addresses->begin(), addresses->end(), address) != addresses->end()) { |
| 264 | return; |
| 265 | } |
| 266 | addresses->push_back(address); |
| 267 | ports[address] = port; |
| 268 | } |
| 269 |
| 270 | void Datacenter::nextAddressOrPort(uint32_t flags) { |
| 271 | uint32_t currentPortNum; |
| 272 | uint32_t currentAddressNum; |
| 273 | std::vector<std::string> *addresses; |
| 274 | if ((flags & 2) != 0) { |
| 275 | if ((flags & 1) != 0) { |
| 276 | currentPortNum = currentPortNumIpv6Download; |
| 277 | currentAddressNum = currentAddressNumIpv6Download; |
| 278 | addresses = &addressesIpv6Download; |
| 279 | } else { |
| 280 | currentPortNum = currentPortNumIpv4Download; |
| 281 | currentAddressNum = currentAddressNumIpv4Download; |
| 282 | addresses = &addressesIpv4Download; |
| 283 | } |
| 284 | } else { |
| 285 | if ((flags & 1) != 0) { |
| 286 | currentPortNum = currentPortNumIpv6; |
| 287 | currentAddressNum = currentAddressNumIpv6; |
| 288 | addresses = &addressesIpv6; |
| 289 | } else { |
| 290 | currentPortNum = currentPortNumIpv4; |
| 291 | currentAddressNum = currentAddressNumIpv4; |
| 292 | addresses = &addressesIpv4; |
| 293 | } |
| 294 | } |
| 295 | if (currentPortNum + 1 < 11) { |
| 296 | currentPortNum++; |
| 297 | } else { |
| 298 | if (currentAddressNum + 1 < addresses->size()) { |
| 299 | currentAddressNum++; |
| 300 | } else { |
| 301 | currentAddressNum = 0; |
| 302 | } |
| 303 | currentPortNum = 0; |
| 304 | } |
| 305 | if ((flags & 2) != 0) { |
| 306 | if ((flags & 1) != 0) { |
| 307 | currentPortNumIpv6Download = currentPortNum; |
| 308 | currentAddressNumIpv6Download = currentAddressNum; |
| 309 | } else { |
| 310 | currentPortNumIpv4Download = currentPortNum; |
| 311 | currentAddressNumIpv4Download = currentAddressNum; |
| 312 | } |
| 313 | } else { |
| 314 | if ((flags & 1) != 0) { |
| 315 | currentPortNumIpv6 = currentPortNum; |
| 316 | currentAddressNumIpv6 = currentAddressNum; |
| 317 | } else { |
| 318 | currentPortNumIpv4 = currentPortNum; |
| 319 | currentAddressNumIpv4 = currentAddressNum; |
| 320 | } |
| 321 | } |
| 322 | } |
| 323 |
| 324 | void Datacenter::storeCurrentAddressAndPortNum() { |
| 325 | if (config == nullptr) { |
| 326 | config = new Config("dc" + to_string_int32(datacenterId) + "conf.dat"); |
| 327 | } |
| 328 | NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(128); |
| 329 | buffer->writeInt32(paramsConfigVersion); |
| 330 | buffer->writeInt32(currentPortNumIpv4); |
| 331 | buffer->writeInt32(currentAddressNumIpv4); |
| 332 | buffer->writeInt32(currentPortNumIpv6); |
| 333 | buffer->writeInt32(currentAddressNumIpv6); |
| 334 | buffer->writeInt32(currentPortNumIpv4Download); |
| 335 | buffer->writeInt32(currentAddressNumIpv4Download); |
| 336 | buffer->writeInt32(currentPortNumIpv6Download); |
| 337 | buffer->writeInt32(currentAddressNumIpv6Download); |
| 338 | config->writeConfig(buffer); |
| 339 | buffer->reuse(); |
| 340 | } |
| 341 |
| 342 | void Datacenter::replaceAddressesAndPorts(std::vector<std::string> &newAddresses, std::map<std::string, uint32_t> &newPorts, uint32_t flags) { |
| 343 | std::vector<std::string> *addresses; |
| 344 | if ((flags & 2) != 0) { |
| 345 | if ((flags & 1) != 0) { |
| 346 | addresses = &addressesIpv6Download; |
| 347 | } else { |
| 348 | addresses = &addressesIpv4Download; |
| 349 | } |
| 350 | } else { |
| 351 | if ((flags & 1) != 0) { |
| 352 | addresses = &addressesIpv6; |
| 353 | } else { |
| 354 | addresses = &addressesIpv4; |
| 355 | } |
| 356 | } |
| 357 | size_t size = addresses->size(); |
| 358 | for (uint32_t a = 0; a < size; a++) { |
| 359 | std::map<std::string, uint32_t>::iterator iter = ports.find((*addresses)[a]); |
| 360 | if (iter != ports.end()) { |
| 361 | ports.erase(iter); |
| 362 | } |
| 363 | } |
| 364 | if ((flags & 2) != 0) { |
| 365 | if ((flags & 1) != 0) { |
| 366 | addressesIpv6Download = newAddresses; |
| 367 | } else { |
| 368 | addressesIpv4Download = newAddresses; |
| 369 | } |
| 370 | } else { |
| 371 | if ((flags & 1) != 0) { |
| 372 | addressesIpv6 = newAddresses; |
| 373 | } else { |
| 374 | addressesIpv4 = newAddresses; |
| 375 | } |
| 376 | } |
| 377 | ports.insert(newPorts.begin(), newPorts.end()); |
| 378 | } |
| 379 |
| 380 | void Datacenter::serializeToStream(NativeByteBuffer *stream) { |
| 381 | stream->writeInt32(configVersion); |
| 382 | stream->writeInt32(datacenterId); |
| 383 | stream->writeInt32(lastInitVersion); |
| 384 | size_t size; |
| 385 | stream->writeInt32((int32_t) (size = addressesIpv4.size())); |
| 386 | for (uint32_t a = 0; a < size; a++) { |
| 387 | stream->writeString(addressesIpv4[a]); |
| 388 | stream->writeInt32(ports[addressesIpv4[a]]); |
| 389 | } |
| 390 | stream->writeInt32((int32_t) (size = addressesIpv6.size())); |
| 391 | for (uint32_t a = 0; a < size; a++) { |
| 392 | stream->writeString(addressesIpv6[a]); |
| 393 | stream->writeInt32(ports[addressesIpv6[a]]); |
| 394 | } |
| 395 | stream->writeInt32((int32_t) (size = addressesIpv4Download.size())); |
| 396 | for (uint32_t a = 0; a < size; a++) { |
| 397 | stream->writeString(addressesIpv4Download[a]); |
| 398 | stream->writeInt32(ports[addressesIpv4Download[a]]); |
| 399 | } |
| 400 | stream->writeInt32((int32_t) (size = addressesIpv6Download.size())); |
| 401 | for (uint32_t a = 0; a < size; a++) { |
| 402 | stream->writeString(addressesIpv6Download[a]); |
| 403 | stream->writeInt32(ports[addressesIpv6Download[a]]); |
| 404 | } |
| 405 | if (authKey != nullptr) { |
| 406 | stream->writeInt32(authKey->length); |
| 407 | stream->writeBytes(authKey); |
| 408 | } else { |
| 409 | stream->writeInt32(0); |
| 410 | } |
| 411 | stream->writeInt64(authKeyId); |
| 412 | stream->writeInt32(authorized ? 1 : 0); |
| 413 | stream->writeInt32((int32_t) (size = serverSalts.size())); |
| 414 | for (uint32_t a = 0; a < size; a++) { |
| 415 | stream->writeInt32(serverSalts[a]->valid_since); |
| 416 | stream->writeInt32(serverSalts[a]->valid_until); |
| 417 | stream->writeInt64(serverSalts[a]->salt); |
| 418 | } |
| 419 | } |
| 420 |
| 421 | void Datacenter::clear() { |
| 422 | authKey = nullptr; |
| 423 | authKeyId = 0; |
| 424 | authorized = false; |
| 425 | serverSalts.clear(); |
| 426 | } |
| 427 |
| 428 | void Datacenter::clearServerSalts() { |
| 429 | serverSalts.clear(); |
| 430 | } |
| 431 |
| 432 | int64_t Datacenter::getServerSalt() { |
| 433 | int32_t date = ConnectionsManager::getInstance().getCurrentTime(); |
| 434 |
| 435 | bool cleanupNeeded = false; |
| 436 |
| 437 | int64_t result = 0; |
| 438 | int32_t maxRemainingInterval = 0; |
| 439 |
| 440 | size_t size = serverSalts.size(); |
| 441 | for (uint32_t a = 0; a < size; a++) { |
| 442 | TL_future_salt *salt = serverSalts[a].get(); |
| 443 | if (salt->valid_until < date) { |
| 444 | cleanupNeeded = true; |
| 445 | } else if (salt->valid_since <= date && salt->valid_until > date) { |
| 446 | if (maxRemainingInterval == 0 || abs(salt->valid_until - date) > maxRemainingInterval) { |
| 447 | maxRemainingInterval = abs(salt->valid_until - date); |
| 448 | result = salt->salt; |
| 449 | } |
| 450 | } |
| 451 | } |
| 452 |
| 453 | if (cleanupNeeded) { |
| 454 | size = serverSalts.size(); |
| 455 | for (uint32_t i = 0; i < size; i++) { |
| 456 | if (serverSalts[i]->valid_until < date) { |
| 457 | serverSalts.erase(serverSalts.begin() + i); |
| 458 | size--; |
| 459 | i--; |
| 460 | } |
| 461 | } |
| 462 | } |
| 463 |
| 464 | if (result == 0) { |
| 465 | DEBUG_D("dc%u valid salt not found", datacenterId); |
| 466 | } |
| 467 |
| 468 | return result; |
| 469 | } |
| 470 |
| 471 | void Datacenter::mergeServerSalts(std::vector<std::unique_ptr<TL_future_salt>> &salts) { |
| 472 | if (salts.empty()) { |
| 473 | return; |
| 474 | } |
| 475 | int32_t date = ConnectionsManager::getInstance().getCurrentTime(); |
| 476 | std::vector<int64_t> existingSalts(serverSalts.size()); |
| 477 | size_t size = serverSalts.size(); |
| 478 | for (uint32_t a = 0; a < size; a++) { |
| 479 | existingSalts.push_back(serverSalts[a]->salt); |
| 480 | } |
| 481 | bool added = false; |
| 482 | size = salts.size(); |
| 483 | for (uint32_t a = 0; a < size; a++) { |
| 484 | int64_t value = salts[a]->salt; |
| 485 | if (std::find(existingSalts.begin(), existingSalts.end(), value) == existingSalts.end() && salts[a]->valid_until > date) { |
| 486 | serverSalts.push_back(std::unique_ptr<TL_future_salt>(std::move(salts[a]))); |
| 487 | added = true; |
| 488 | } |
| 489 | } |
| 490 | if (added) { |
| 491 | std::sort(serverSalts.begin(), serverSalts.end(), [](const std::unique_ptr<TL_future_salt> &x, const std::unique_ptr<TL_future_salt> &y) { return x->valid_since < y->valid_since; }); |
| 492 | } |
| 493 | } |
| 494 |
| 495 | void Datacenter::addServerSalt(std::unique_ptr<TL_future_salt> &serverSalt) { |
| 496 | size_t size = serverSalts.size(); |
| 497 | for (uint32_t a = 0; a < size; a++) { |
| 498 | if (serverSalts[a]->salt == serverSalt->salt) { |
| 499 | return; |
| 500 | } |
| 501 | } |
| 502 | serverSalts.push_back(std::move(serverSalt)); |
| 503 | std::sort(serverSalts.begin(), serverSalts.end(), [](const std::unique_ptr<TL_future_salt> &x, const std::unique_ptr<TL_future_salt> &y) { return x->valid_since < y->valid_since; }); |
| 504 | } |
| 505 |
| 506 | bool Datacenter::containsServerSalt(int64_t value) { |
| 507 | size_t size = serverSalts.size(); |
| 508 | for (uint32_t a = 0; a < size; a++) { |
| 509 | if (serverSalts[a]->salt == value) { |
| 510 | return true; |
| 511 | } |
| 512 | } |
| 513 | return false; |
| 514 | } |
| 515 |
| 516 | void Datacenter::suspendConnections() { |
| 517 | if (genericConnection != nullptr) { |
| 518 | genericConnection->suspendConnection(); |
| 519 | } |
| 520 | if (uploadConnection != nullptr) { |
| 521 | uploadConnection->suspendConnection(); |
| 522 | } |
| 523 | for (uint32_t a = 0; a < DOWNLOAD_CONNECTIONS_COUNT; a++) { |
| 524 | if (downloadConnections[a] != nullptr) { |
| 525 | downloadConnections[a]->suspendConnection(); |
| 526 | } |
| 527 | } |
| 528 | } |
| 529 |
| 530 | void Datacenter::getSessions(std::vector<int64_t> &sessions) { |
| 531 | if (genericConnection != nullptr) { |
| 532 | sessions.push_back(genericConnection->getSissionId()); |
| 533 | } |
| 534 | if (uploadConnection != nullptr) { |
| 535 | sessions.push_back(uploadConnection->getSissionId()); |
| 536 | } |
| 537 | for (uint32_t a = 0; a < DOWNLOAD_CONNECTIONS_COUNT; a++) { |
| 538 | if (downloadConnections[a] != nullptr) { |
| 539 | sessions.push_back(downloadConnections[a]->getSissionId()); |
| 540 | } |
| 541 | } |
| 542 | } |
| 543 |
| 544 | void Datacenter::recreateSessions() { |
| 545 | if (genericConnection != nullptr) { |
| 546 | genericConnection->recreateSession(); |
| 547 | } |
| 548 | if (uploadConnection != nullptr) { |
| 549 | uploadConnection->recreateSession(); |
| 550 | } |
| 551 | for (uint32_t a = 0; a < DOWNLOAD_CONNECTIONS_COUNT; a++) { |
| 552 | if (downloadConnections[a] != nullptr) { |
| 553 | downloadConnections[a]->recreateSession(); |
| 554 | } |
| 555 | } |
| 556 | } |
| 557 |
| 558 | Connection *Datacenter::createDownloadConnection(uint32_t num) { |
| 559 | if (downloadConnections[num] == nullptr) { |
| 560 | downloadConnections[num] = new Connection(this, ConnectionTypeDownload); |
| 561 | } |
| 562 | return downloadConnections[num]; |
| 563 | } |
| 564 |
| 565 | Connection *Datacenter::createUploadConnection() { |
| 566 | if (uploadConnection == nullptr) { |
| 567 | uploadConnection = new Connection(this, ConnectionTypeUpload); |
| 568 | } |
| 569 | return uploadConnection; |
| 570 | } |
| 571 |
| 572 | Connection *Datacenter::createGenericConnection() { |
| 573 | if (genericConnection == nullptr) { |
| 574 | genericConnection = new Connection(this, ConnectionTypeGeneric); |
| 575 | } |
| 576 | return genericConnection; |
| 577 | } |
| 578 |
| 579 | Connection *Datacenter::createPushConnection() { |
| 580 | if (pushConnection == nullptr) { |
| 581 | pushConnection = new Connection(this, ConnectionTypePush); |
| 582 | } |
| 583 | return pushConnection; |
| 584 | } |
| 585 |
| 586 | uint32_t Datacenter::getDatacenterId() { |
| 587 | return datacenterId; |
| 588 | } |
| 589 |
| 590 | bool Datacenter::isHandshaking() { |
| 591 | return handshakeState != 0; |
| 592 | } |
| 593 |
| 594 | void Datacenter::beginHandshake(bool reconnect) { |
| 595 | DEBUG_D("dc%u handshake: begin", datacenterId); |
| 596 | cleanupHandshake(); |
| 597 | createGenericConnection()->recreateSession(); |
| 598 | handshakeState = 1; |
| 599 |
| 600 | if (reconnect) { |
| 601 | createGenericConnection()->suspendConnection(); |
| 602 | createGenericConnection()->connect(); |
| 603 | } |
| 604 |
| 605 | TL_req_pq *request = new TL_req_pq(); |
| 606 | request->nonce = std::unique_ptr<ByteArray>(new ByteArray(16)); |
| 607 | RAND_bytes(request->nonce->bytes, 16); |
| 608 | authNonce = new ByteArray(request->nonce.get()); |
| 609 | sendRequestData(request, true); |
| 610 | } |
| 611 |
| 612 | void Datacenter::cleanupHandshake() { |
| 613 | handshakeState = 0; |
| 614 | if (handshakeRequest != nullptr) { |
| 615 | delete handshakeRequest; |
| 616 | handshakeRequest = nullptr; |
| 617 | } |
| 618 | if (handshakeServerSalt != nullptr) { |
| 619 | delete handshakeServerSalt; |
| 620 | handshakeServerSalt = nullptr; |
| 621 | } |
| 622 | if (authNonce != nullptr) { |
| 623 | delete authNonce; |
| 624 | authNonce = nullptr; |
| 625 | } |
| 626 | if (authServerNonce != nullptr) { |
| 627 | delete authServerNonce; |
| 628 | authServerNonce = nullptr; |
| 629 | } |
| 630 | if (authNewNonce != nullptr) { |
| 631 | delete authNewNonce; |
| 632 | authNewNonce = nullptr; |
| 633 | } |
| 634 | if (handshakeAuthKey != nullptr) { |
| 635 | delete handshakeAuthKey; |
| 636 | handshakeAuthKey = nullptr; |
| 637 | } |
| 638 | } |
| 639 |
| 640 | void Datacenter::sendRequestData(TLObject *object, bool important) { |
| 641 | uint32_t messageLength = object->getObjectSize(); |
| 642 | NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(20 + messageLength); |
| 643 | buffer->writeInt64(0); |
| 644 | buffer->writeInt64(ConnectionsManager::getInstance().generateMessageId()); |
| 645 | buffer->writeInt32(messageLength); |
| 646 | object->serializeToStream(buffer); |
| 647 | createGenericConnection()->sendData(buffer, false); |
| 648 | if (important) { |
| 649 | if (handshakeRequest != object) { |
| 650 | if (handshakeRequest != nullptr) { |
| 651 | delete handshakeRequest; |
| 652 | } |
| 653 | handshakeRequest = object; |
| 654 | } |
| 655 | } else { |
| 656 | delete object; |
| 657 | } |
| 658 | } |
| 659 |
| 660 | void Datacenter::onHandshakeConnectionClosed(Connection *connection) { |
| 661 | if (handshakeState == 0) { |
| 662 | return; |
| 663 | } |
| 664 | needResendData = true; |
| 665 | } |
| 666 |
| 667 | void Datacenter::onHandshakeConnectionConnected(Connection *connection) { |
| 668 | if (handshakeState == 0 || !needResendData) { |
| 669 | return; |
| 670 | } |
| 671 | beginHandshake(false); |
| 672 | } |
| 673 |
| 674 | inline uint64_t gcd(uint64_t a, uint64_t b) { |
| 675 | while (a != 0 && b != 0) { |
| 676 | while ((b & 1) == 0) { |
| 677 | b >>= 1; |
| 678 | } |
| 679 | while ((a & 1) == 0) { |
| 680 | a >>= 1; |
| 681 | } |
| 682 | if (a > b) { |
| 683 | a -= b; |
| 684 | } else { |
| 685 | b -= a; |
| 686 | } |
| 687 | } |
| 688 | return b == 0 ? a : b; |
| 689 | } |
| 690 |
| 691 | inline bool factorizeValue(uint64_t what, uint32_t &p, uint32_t &q) { |
| 692 | int32_t it = 0, i, j; |
| 693 | uint64_t g = 0; |
| 694 | for (i = 0; i < 3 || it < 1000; i++) { |
| 695 | uint64_t t = ((lrand48() & 15) + 17) % what; |
| 696 | uint64_t x = (long long) lrand48() % (what - 1) + 1, y = x; |
| 697 | int32_t lim = 1 << (i + 18); |
| 698 | for (j = 1; j < lim; j++) { |
| 699 | ++it; |
| 700 | uint64_t a = x, b = x, c = t; |
| 701 | while (b) { |
| 702 | if (b & 1) { |
| 703 | c += a; |
| 704 | if (c >= what) { |
| 705 | c -= what; |
| 706 | } |
| 707 | } |
| 708 | a += a; |
| 709 | if (a >= what) { |
| 710 | a -= what; |
| 711 | } |
| 712 | b >>= 1; |
| 713 | } |
| 714 | x = c; |
| 715 | uint64_t z = x < y ? what + x - y : x - y; |
| 716 | g = gcd(z, what); |
| 717 | if (g != 1) { |
| 718 | break; |
| 719 | } |
| 720 | if (!(j & (j - 1))) { |
| 721 | y = x; |
| 722 | } |
| 723 | } |
| 724 | if (g > 1 && g < what) { |
| 725 | break; |
| 726 | } |
| 727 | } |
| 728 |
| 729 | if (g > 1 && g < what) { |
| 730 | p = (uint32_t) g; |
| 731 | q = (uint32_t) (what / g); |
| 732 | if (p > q) { |
| 733 | uint32_t tmp = p; |
| 734 | p = q; |
| 735 | q = tmp; |
| 736 | } |
| 737 | return true; |
| 738 | } else { |
| 739 | DEBUG_E("factorization failed for %llu", what); |
| 740 | p = 0; |
| 741 | q = 0; |
| 742 | return false; |
| 743 | } |
| 744 | } |
| 745 |
| 746 | inline bool check_prime(BIGNUM *p) { |
| 747 | int result = 0; |
| 748 | if (!BN_primality_test(&result, p, BN_prime_checks, bnContext, 0, NULL)) { |
| 749 | DEBUG_E("OpenSSL error at BN_primality_test"); |
| 750 | return false; |
| 751 | } |
| 752 | return result != 0; |
| 753 | } |
| 754 |
| 755 | inline bool isGoodPrime(BIGNUM *p, uint32_t g) { |
| 756 | //TODO check against known good primes |
| 757 | if (g < 2 || g > 7 || BN_num_bits(p) != 2048) { |
| 758 | return false; |
| 759 | } |
| 760 |
| 761 | BIGNUM *t = BN_new(); |
| 762 | BIGNUM *dh_g = BN_new(); |
| 763 |
| 764 | if (!BN_set_word(dh_g, 4 * g)) { |
| 765 | DEBUG_E("OpenSSL error at BN_set_word(dh_g, 4 * g)"); |
| 766 | BN_free(t); |
| 767 | BN_free(dh_g); |
| 768 | return false; |
| 769 | } |
| 770 | if (!BN_mod(t, p, dh_g, bnContext)) { |
| 771 | DEBUG_E("OpenSSL error at BN_mod"); |
| 772 | BN_free(t); |
| 773 | BN_free(dh_g); |
| 774 | return false; |
| 775 | } |
| 776 | uint64_t x = BN_get_word(t); |
| 777 | if (x >= 4 * g) { |
| 778 | DEBUG_E("OpenSSL error at BN_get_word"); |
| 779 | BN_free(t); |
| 780 | BN_free(dh_g); |
| 781 | return false; |
| 782 | } |
| 783 |
| 784 | BN_free(dh_g); |
| 785 |
| 786 | bool result = true; |
| 787 | switch (g) { |
| 788 | case 2: |
| 789 | if (x != 7) { |
| 790 | result = false; |
| 791 | } |
| 792 | break; |
| 793 | case 3: |
| 794 | if (x % 3 != 2) { |
| 795 | result = false; |
| 796 | } |
| 797 | break; |
| 798 | case 5: |
| 799 | if (x % 5 != 1 && x % 5 != 4) { |
| 800 | result = false; |
| 801 | } |
| 802 | break; |
| 803 | case 6: |
| 804 | if (x != 19 && x != 23) { |
| 805 | result = false; |
| 806 | } |
| 807 | break; |
| 808 | case 7: |
| 809 | if (x % 7 != 3 && x % 7 != 5 && x % 7 != 6) { |
| 810 | result = false; |
| 811 | } |
| 812 | break; |
| 813 | default: |
| 814 | break; |
| 815 | } |
| 816 |
| 817 | char *prime = BN_bn2hex(p); |
| 818 | static const char *goodPrime = "c71caeb9c6b1c9048e6c522f70f13f73980d40238e3e21c14934d037563d930f48198a0aa7c14058229493d22530f4dbfa336f6e0ac925139543aed44cce7c3720fd51f69458705ac68cd4fe6b6b13abdc9746512969328454f18faf8c595f642477fe96bb2a941d5bcd1d4ac8cc49880708fa9b378e3c4f3a9060bee67cf9a4a4a695811051907e162753b56b0f6b410dba74d8a84b2a14b3144e0ef1284754fd17ed950d5965b4b9dd46582db1178d169c6bc465b0d6ff9ca3928fef5b9ae4e418fc15e83ebea0f87fa9ff5eed70050ded2849f47bf959d956850ce929851f0d8115f635b105ee2e4e15d04b2454bf6f4fadf034b10403119cd8e3b92fcc5b"; |
| 819 | if (!strcasecmp(prime, goodPrime)) { |
| 820 | delete [] prime; |
| 821 | BN_free(t); |
| 822 | return true; |
| 823 | } |
| 824 | delete [] prime; |
| 825 |
| 826 | if (!result || !check_prime(p)) { |
| 827 | BN_free(t); |
| 828 | return false; |
| 829 | } |
| 830 |
| 831 | BIGNUM *b = BN_new(); |
| 832 | if (!BN_set_word(b, 2)) { |
| 833 | DEBUG_E("OpenSSL error at BN_set_word(b, 2)"); |
| 834 | BN_free(b); |
| 835 | BN_free(t); |
| 836 | return false; |
| 837 | } |
| 838 | if (!BN_div(t, 0, p, b, bnContext)) { |
| 839 | DEBUG_E("OpenSSL error at BN_div"); |
| 840 | BN_free(b); |
| 841 | BN_free(t); |
| 842 | return false; |
| 843 | } |
| 844 | if (!check_prime(t)) { |
| 845 | result = false; |
| 846 | } |
| 847 | BN_free(b); |
| 848 | BN_free(t); |
| 849 | return result; |
| 850 | } |
| 851 |
| 852 | inline bool isGoodGaAndGb(BIGNUM *g_a, BIGNUM *p) { |
| 853 | if (BN_num_bytes(g_a) > 256 || BN_num_bits(g_a) < 2048 - 64 || BN_cmp(p, g_a) <= 0) { |
| 854 | return false; |
| 855 | } |
| 856 | BIGNUM *dif = BN_new(); |
| 857 | BN_sub(dif, p, g_a); |
| 858 | if (BN_num_bits(dif) < 2048 - 64) { |
| 859 | BN_free(dif); |
| 860 | return false; |
| 861 | } |
| 862 | BN_free(dif); |
| 863 | return true; |
| 864 | } |
| 865 |
| 866 | void Datacenter::aesIgeEncryption(uint8_t *buffer, uint8_t *key, uint8_t *iv, bool encrypt, bool changeIv, uint32_t length) { |
| 867 | uint8_t *ivBytes = iv; |
| 868 | if (!changeIv) { |
| 869 | ivBytes = new uint8_t[32]; |
| 870 | memcpy(ivBytes, iv, 32); |
| 871 | } |
| 872 | AES_KEY akey; |
| 873 | if (!encrypt) { |
| 874 | AES_set_decrypt_key(key, 32 * 8, &akey); |
| 875 | AES_ige_encrypt(buffer, buffer, length, &akey, ivBytes, AES_DECRYPT); |
| 876 | } else { |
| 877 | AES_set_encrypt_key(key, 32 * 8, &akey); |
| 878 | AES_ige_encrypt(buffer, buffer, length, &akey, ivBytes, AES_ENCRYPT); |
| 879 | } |
| 880 | if (!changeIv) { |
| 881 | delete [] ivBytes; |
| 882 | } |
| 883 | } |
| 884 |
| 885 | int32_t Datacenter::selectPublicKey(std::vector<int64_t> &fingerprints) { |
| 886 | if (serverPublicKeys.empty()) { |
| 887 | serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" |
| 888 | "MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6\n" |
| 889 | "lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS\n" |
| 890 | "an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw\n" |
| 891 | "Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+\n" |
| 892 | "8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n\n" |
| 893 | "Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB\n" |
| 894 | "-----END RSA PUBLIC KEY-----"); |
| 895 | serverPublicKeysFingerprints.push_back(0xc3b42b026ce86b21LL); |
| 896 |
| 897 | serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" |
| 898 | "MIIBCgKCAQEAxq7aeLAqJR20tkQQMfRn+ocfrtMlJsQ2Uksfs7Xcoo77jAid0bRt\n" |
| 899 | "ksiVmT2HEIJUlRxfABoPBV8wY9zRTUMaMA654pUX41mhyVN+XoerGxFvrs9dF1Ru\n" |
| 900 | "vCHbI02dM2ppPvyytvvMoefRoL5BTcpAihFgm5xCaakgsJ/tH5oVl74CdhQw8J5L\n" |
| 901 | "xI/K++KJBUyZ26Uba1632cOiq05JBUW0Z2vWIOk4BLysk7+U9z+SxynKiZR3/xdi\n" |
| 902 | "XvFKk01R3BHV+GUKM2RYazpS/P8v7eyKhAbKxOdRcFpHLlVwfjyM1VlDQrEZxsMp\n" |
| 903 | "NTLYXb6Sce1Uov0YtNx5wEowlREH1WOTlwIDAQAB\n" |
| 904 | "-----END RSA PUBLIC KEY-----"); |
| 905 | serverPublicKeysFingerprints.push_back(0x9a996a1db11c729bLL); |
| 906 |
| 907 | serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" |
| 908 | "MIIBCgKCAQEAsQZnSWVZNfClk29RcDTJQ76n8zZaiTGuUsi8sUhW8AS4PSbPKDm+\n" |
| 909 | "DyJgdHDWdIF3HBzl7DHeFrILuqTs0vfS7Pa2NW8nUBwiaYQmPtwEa4n7bTmBVGsB\n" |
| 910 | "1700/tz8wQWOLUlL2nMv+BPlDhxq4kmJCyJfgrIrHlX8sGPcPA4Y6Rwo0MSqYn3s\n" |
| 911 | "g1Pu5gOKlaT9HKmE6wn5Sut6IiBjWozrRQ6n5h2RXNtO7O2qCDqjgB2vBxhV7B+z\n" |
| 912 | "hRbLbCmW0tYMDsvPpX5M8fsO05svN+lKtCAuz1leFns8piZpptpSCFn7bWxiA9/f\n" |
| 913 | "x5x17D7pfah3Sy2pA+NDXyzSlGcKdaUmwQIDAQAB\n" |
| 914 | "-----END RSA PUBLIC KEY-----"); |
| 915 | serverPublicKeysFingerprints.push_back(0xb05b2a6f70cdea78LL); |
| 916 |
| 917 | serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" |
| 918 | "MIIBCgKCAQEAwqjFW0pi4reKGbkc9pK83Eunwj/k0G8ZTioMMPbZmW99GivMibwa\n" |
| 919 | "xDM9RDWabEMyUtGoQC2ZcDeLWRK3W8jMP6dnEKAlvLkDLfC4fXYHzFO5KHEqF06i\n" |
| 920 | "qAqBdmI1iBGdQv/OQCBcbXIWCGDY2AsiqLhlGQfPOI7/vvKc188rTriocgUtoTUc\n" |
| 921 | "/n/sIUzkgwTqRyvWYynWARWzQg0I9olLBBC2q5RQJJlnYXZwyTL3y9tdb7zOHkks\n" |
| 922 | "WV9IMQmZmyZh/N7sMbGWQpt4NMchGpPGeJ2e5gHBjDnlIf2p1yZOYeUYrdbwcS0t\n" |
| 923 | "UiggS4UeE8TzIuXFQxw7fzEIlmhIaq3FnwIDAQAB\n" |
| 924 | "-----END RSA PUBLIC KEY-----"); |
| 925 | serverPublicKeysFingerprints.push_back(0x71e025b6c76033e3LL); |
| 926 | } |
| 927 |
| 928 | size_t count1 = fingerprints.size(); |
| 929 | size_t count2 = serverPublicKeysFingerprints.size(); |
| 930 | for (uint32_t a = 0; a < count1; a++) { |
| 931 | for (uint32_t b = 0; b < count2; b++) { |
| 932 | if ((uint64_t) fingerprints[a] == serverPublicKeysFingerprints[b]) { |
| 933 | return b; |
| 934 | } |
| 935 | } |
| 936 | } |
| 937 | return -1; |
| 938 | } |
| 939 |
| 940 | void Datacenter::processHandshakeResponse(TLObject *message, int64_t messageId) { |
| 941 | if (handshakeState == 0) { |
| 942 | return; |
| 943 | } |
| 944 | const std::type_info &typeInfo = typeid(*message); |
| 945 | if (typeInfo == typeid(TL_resPQ)) { |
| 946 | if (handshakeState != 1) { |
| 947 | sendAckRequest(messageId); |
| 948 | return; |
| 949 | } |
| 950 |
| 951 | handshakeState = 2; |
| 952 | TL_resPQ *result = (TL_resPQ *) message; |
| 953 | if (authNonce->isEqualTo(result->nonce.get())) { |
| 954 | int32_t keyIndex = selectPublicKey(result->server_public_key_fingerprints); |
| 955 | if (keyIndex < 0) { |
| 956 | DEBUG_E("dc%u handshake: can't find valid server public key", datacenterId); |
| 957 | beginHandshake(false); |
| 958 | return; |
| 959 | } |
| 960 |
| 961 | authServerNonce = new ByteArray(result->server_nonce.get()); |
| 962 |
| 963 | //TODO run in different thread? |
| 964 | uint64_t pq = ((uint64_t) (result->pq->bytes[0] & 0xff) << 56) | |
| 965 | ((uint64_t) (result->pq->bytes[1] & 0xff) << 48) | |
| 966 | ((uint64_t) (result->pq->bytes[2] & 0xff) << 40) | |
| 967 | ((uint64_t) (result->pq->bytes[3] & 0xff) << 32) | |
| 968 | ((uint64_t) (result->pq->bytes[4] & 0xff) << 24) | |
| 969 | ((uint64_t) (result->pq->bytes[5] & 0xff) << 16) | |
| 970 | ((uint64_t) (result->pq->bytes[6] & 0xff) << 8) | |
| 971 | ((uint64_t) (result->pq->bytes[7] & 0xff)); |
| 972 | uint32_t p, q; |
| 973 | if (!factorizeValue(pq, p, q)) { |
| 974 | beginHandshake(false); |
| 975 | return; |
| 976 | } |
| 977 |
| 978 | TL_req_DH_params *request = new TL_req_DH_params(); |
| 979 | request->nonce = std::unique_ptr<ByteArray>(new ByteArray(authNonce)); |
| 980 | request->server_nonce = std::unique_ptr<ByteArray>(new ByteArray(authServerNonce)); |
| 981 | request->p = std::unique_ptr<ByteArray>(new ByteArray(4)); |
| 982 | request->p->bytes[3] = (uint8_t) p; |
| 983 | request->p->bytes[2] = (uint8_t) (p >> 8); |
| 984 | request->p->bytes[1] = (uint8_t) (p >> 16); |
| 985 | request->p->bytes[0] = (uint8_t) (p >> 24); |
| 986 | request->q = std::unique_ptr<ByteArray>(new ByteArray(4)); |
| 987 | request->q->bytes[3] = (uint8_t) q; |
| 988 | request->q->bytes[2] = (uint8_t) (q >> 8); |
| 989 | request->q->bytes[1] = (uint8_t) (q >> 16); |
| 990 | request->q->bytes[0] = (uint8_t) (q >> 24); |
| 991 | request->public_key_fingerprint = (int64_t) serverPublicKeysFingerprints[keyIndex]; |
| 992 |
| 993 | TL_p_q_inner_data *innerData = new TL_p_q_inner_data(); |
| 994 | innerData->nonce = std::unique_ptr<ByteArray>(new ByteArray(authNonce)); |
| 995 | innerData->server_nonce = std::unique_ptr<ByteArray>(new ByteArray(authServerNonce)); |
| 996 | innerData->pq = std::unique_ptr<ByteArray>(new ByteArray(result->pq.get())); |
| 997 | innerData->p = std::unique_ptr<ByteArray>(new ByteArray(request->p.get())); |
| 998 | innerData->q = std::unique_ptr<ByteArray>(new ByteArray(request->q.get())); |
| 999 | innerData->new_nonce = std::unique_ptr<ByteArray>(new ByteArray(32)); |
| 1000 | RAND_bytes(innerData->new_nonce->bytes, 32); |
| 1001 | authNewNonce = new ByteArray(innerData->new_nonce.get()); |
| 1002 |
| 1003 | uint32_t innerDataSize = innerData->getObjectSize(); |
| 1004 | uint32_t additionalSize = innerDataSize + SHA_DIGEST_LENGTH < 255 ? 255 - (innerDataSize + SHA_DIGEST_LENGTH) : 0; |
| 1005 | NativeByteBuffer *innerDataBuffer = BuffersStorage::getInstance().getFreeBuffer(innerDataSize + additionalSize + SHA_DIGEST_LENGTH); |
| 1006 | innerDataBuffer->position(SHA_DIGEST_LENGTH); |
| 1007 | innerData->serializeToStream(innerDataBuffer); |
| 1008 | delete innerData; |
| 1009 |
| 1010 | SHA1(innerDataBuffer->bytes() + SHA_DIGEST_LENGTH, innerDataSize, innerDataBuffer->bytes()); |
| 1011 | if (additionalSize != 0) { |
| 1012 | RAND_bytes(innerDataBuffer->bytes() + SHA_DIGEST_LENGTH + innerDataSize, additionalSize); |
| 1013 | } |
| 1014 |
| 1015 | std::string &key = serverPublicKeys[keyIndex]; |
| 1016 |
| 1017 | BIO *keyBio = BIO_new(BIO_s_mem()); |
| 1018 | BIO_write(keyBio, key.c_str(), (int) key.length()); |
| 1019 | RSA *rsaKey = PEM_read_bio_RSAPublicKey(keyBio, NULL, NULL, NULL); |
| 1020 | BIO_free(keyBio); |
| 1021 | if (bnContext == nullptr) { |
| 1022 | bnContext = BN_CTX_new(); |
| 1023 | } |
| 1024 | BIGNUM *a = BN_bin2bn(innerDataBuffer->bytes(), innerDataBuffer->limit(), NULL); |
| 1025 | BIGNUM *r = BN_new(); |
| 1026 | BN_mod_exp(r, a, rsaKey->e, rsaKey->n, bnContext); |
| 1027 | uint32_t size = BN_num_bytes(r); |
| 1028 | ByteArray *rsaEncryptedData = new ByteArray(size >= 256 ? size : 256); |
| 1029 | size_t resLen = BN_bn2bin(r, rsaEncryptedData->bytes); |
| 1030 | if (256 - resLen > 0) { |
| 1031 | memset(rsaEncryptedData + resLen, 0, 256 - resLen); |
| 1032 | } |
| 1033 | BN_free(a); |
| 1034 | BN_free(r); |
| 1035 | RSA_free(rsaKey); |
| 1036 | innerDataBuffer->reuse(); |
| 1037 |
| 1038 | request->encrypted_data = std::unique_ptr<ByteArray>(rsaEncryptedData); |
| 1039 |
| 1040 | sendAckRequest(messageId); |
| 1041 | sendRequestData(request, true); |
| 1042 | } else { |
| 1043 | DEBUG_E("dc%u handshake: invalid client nonce", datacenterId); |
| 1044 | beginHandshake(false); |
| 1045 | } |
| 1046 | } else if (dynamic_cast<Server_DH_Params *>(message)) { |
| 1047 | if (typeInfo == typeid(TL_server_DH_params_ok)) { |
| 1048 | if (handshakeState != 2) { |
| 1049 | sendAckRequest(messageId); |
| 1050 | return; |
| 1051 | } |
| 1052 |
| 1053 | handshakeState = 3; |
| 1054 |
| 1055 | TL_server_DH_params_ok *result = (TL_server_DH_params_ok *) message; |
| 1056 |
| 1057 | NativeByteBuffer *tmpAesKeyAndIv = BuffersStorage::getInstance().getFreeBuffer(84); |
| 1058 |
| 1059 | NativeByteBuffer *newNonceAndServerNonce = BuffersStorage::getInstance().getFreeBuffer(authNewNonce->length + authServerNonce->length); |
| 1060 | newNonceAndServerNonce->writeBytes(authNewNonce); |
| 1061 | newNonceAndServerNonce->writeBytes(authServerNonce); |
| 1062 | SHA1(newNonceAndServerNonce->bytes(), newNonceAndServerNonce->limit(), tmpAesKeyAndIv->bytes()); |
| 1063 | newNonceAndServerNonce->reuse(); |
| 1064 |
| 1065 | NativeByteBuffer *serverNonceAndNewNonce = BuffersStorage::getInstance().getFreeBuffer(authServerNonce->length + authNewNonce->length); |
| 1066 | serverNonceAndNewNonce->writeBytes(authServerNonce); |
| 1067 | serverNonceAndNewNonce->writeBytes(authNewNonce); |
| 1068 | SHA1(serverNonceAndNewNonce->bytes(), serverNonceAndNewNonce->limit(), tmpAesKeyAndIv->bytes() + 20); |
| 1069 | serverNonceAndNewNonce->reuse(); |
| 1070 |
| 1071 | NativeByteBuffer *newNonceAndNewNonce = BuffersStorage::getInstance().getFreeBuffer(authNewNonce->length + authNewNonce->length); |
| 1072 | newNonceAndNewNonce->writeBytes(authNewNonce); |
| 1073 | newNonceAndNewNonce->writeBytes(authNewNonce); |
| 1074 | SHA1(newNonceAndNewNonce->bytes(), newNonceAndNewNonce->limit(), tmpAesKeyAndIv->bytes() + 40); |
| 1075 | newNonceAndNewNonce->reuse(); |
| 1076 |
| 1077 | memcpy(tmpAesKeyAndIv->bytes() + 60, authNewNonce->bytes, 4); |
| 1078 | aesIgeEncryption(result->encrypted_answer->bytes, tmpAesKeyAndIv->bytes(), tmpAesKeyAndIv->bytes() + 32, false, false, result->encrypted_answer->length); |
| 1079 |
| 1080 | bool hashVerified = false; |
| 1081 | for (uint32_t i = 0; i < 16; i++) { |
| 1082 | SHA1(result->encrypted_answer->bytes + SHA_DIGEST_LENGTH, result->encrypted_answer->length - i - SHA_DIGEST_LENGTH, tmpAesKeyAndIv->bytes() + 64); |
| 1083 | if (!memcmp(tmpAesKeyAndIv->bytes() + 64, result->encrypted_answer->bytes, SHA_DIGEST_LENGTH)) { |
| 1084 | hashVerified = true; |
| 1085 | break; |
| 1086 | } |
| 1087 | } |
| 1088 |
| 1089 | if (!hashVerified) { |
| 1090 | DEBUG_E("dc%u handshake: can't decode DH params", datacenterId); |
| 1091 | beginHandshake(false); |
| 1092 | return; |
| 1093 | } |
| 1094 |
| 1095 | bool error = false; |
| 1096 | NativeByteBuffer *answerWithHash = new NativeByteBuffer(result->encrypted_answer->bytes + SHA_DIGEST_LENGTH, result->encrypted_answer->length - SHA_DIGEST_LENGTH); |
| 1097 | uint32_t constructor = answerWithHash->readUint32(&error); |
| 1098 | TL_server_DH_inner_data *dhInnerData = TL_server_DH_inner_data::TLdeserialize(answerWithHash, constructor, error); |
| 1099 | delete answerWithHash; |
| 1100 |
| 1101 | if (error) { |
| 1102 | DEBUG_E("dc%u handshake: can't parse decoded DH params", datacenterId); |
| 1103 | beginHandshake(false); |
| 1104 | return; |
| 1105 | } |
| 1106 |
| 1107 | if (!authNonce->isEqualTo(dhInnerData->nonce.get())) { |
| 1108 | DEBUG_E("dc%u handshake: invalid DH nonce", datacenterId); |
| 1109 | beginHandshake(false); |
| 1110 | return; |
| 1111 | } |
| 1112 |
| 1113 | if (!authServerNonce->isEqualTo(dhInnerData->server_nonce.get())) { |
| 1114 | DEBUG_E("dc%u handshake: invalid DH server nonce", datacenterId); |
| 1115 | beginHandshake(false); |
| 1116 | return; |
| 1117 | } |
| 1118 |
| 1119 | BIGNUM *p = BN_bin2bn(dhInnerData->dh_prime->bytes, dhInnerData->dh_prime->length, NULL); |
| 1120 | if (p == nullptr) { |
| 1121 | DEBUG_E("can't allocate BIGNUM p"); |
| 1122 | exit(1); |
| 1123 | } |
| 1124 | if (!isGoodPrime(p, dhInnerData->g)) { |
| 1125 | DEBUG_E("dc%u handshake: bad prime", datacenterId); |
| 1126 | beginHandshake(false); |
| 1127 | BN_free(p); |
| 1128 | return; |
| 1129 | } |
| 1130 |
| 1131 | BIGNUM *g_a = BN_new(); |
| 1132 | if (g_a == nullptr) { |
| 1133 | DEBUG_E("can't allocate BIGNUM g_a"); |
| 1134 | exit(1); |
| 1135 | } |
| 1136 | BN_bin2bn(dhInnerData->g_a->bytes, dhInnerData->g_a->length, g_a); |
| 1137 | if (!isGoodGaAndGb(g_a, p)) { |
| 1138 | DEBUG_E("dc%u handshake: bad prime and g_a", datacenterId); |
| 1139 | beginHandshake(false); |
| 1140 | BN_free(p); |
| 1141 | BN_free(g_a); |
| 1142 | return; |
| 1143 | } |
| 1144 |
| 1145 | BIGNUM *g = BN_new(); |
| 1146 | if (g == nullptr) { |
| 1147 | DEBUG_E("can't allocate BIGNUM g"); |
| 1148 | exit(1); |
| 1149 | } |
| 1150 | if (!BN_set_word(g, dhInnerData->g)) { |
| 1151 | DEBUG_E("OpenSSL error at BN_set_word(g_b, dhInnerData->g)"); |
| 1152 | beginHandshake(false); |
| 1153 | BN_free(g); |
| 1154 | BN_free(g_a); |
| 1155 | BN_free(p); |
| 1156 | return; |
| 1157 | } |
| 1158 | static uint8_t bytes[256]; |
| 1159 | RAND_bytes(bytes, 256); |
| 1160 | BIGNUM *b = BN_bin2bn(bytes, 256, NULL); |
| 1161 | if (b == nullptr) { |
| 1162 | DEBUG_E("can't allocate BIGNUM b"); |
| 1163 | exit(1); |
| 1164 | } |
| 1165 |
| 1166 | BIGNUM *g_b = BN_new(); |
| 1167 | if (!BN_mod_exp(g_b, g, b, p, bnContext)) { |
| 1168 | DEBUG_E("OpenSSL error at BN_mod_exp(g_b, g, b, p, bnContext)"); |
| 1169 | beginHandshake(false); |
| 1170 | BN_free(g); |
| 1171 | BN_free(g_a); |
| 1172 | BN_free(g_b); |
| 1173 | BN_free(b); |
| 1174 | BN_free(p); |
| 1175 | return; |
| 1176 | } |
| 1177 |
| 1178 | TL_client_DH_inner_data *clientInnerData = new TL_client_DH_inner_data(); |
| 1179 | clientInnerData->g_b = std::unique_ptr<ByteArray>(new ByteArray(BN_num_bytes(g_b))); |
| 1180 | BN_bn2bin(g_b, clientInnerData->g_b->bytes); |
| 1181 | clientInnerData->nonce = std::unique_ptr<ByteArray>(new ByteArray(authNonce)); |
| 1182 | clientInnerData->server_nonce = std::unique_ptr<ByteArray>(new ByteArray(authServerNonce)); |
| 1183 | clientInnerData->retry_id = 0; |
| 1184 | BN_free(g_b); |
| 1185 | BN_free(g); |
| 1186 |
| 1187 | BIGNUM *authKeyNum = BN_new(); |
| 1188 | BN_mod_exp(authKeyNum, g_a, b, p, bnContext); |
| 1189 | size_t l = BN_num_bytes(authKeyNum); |
| 1190 | handshakeAuthKey = new ByteArray(256); |
| 1191 | BN_bn2bin(authKeyNum, handshakeAuthKey->bytes); |
| 1192 | if (l < 256) { |
| 1193 | memmove(handshakeAuthKey->bytes + 256 - l, handshakeAuthKey->bytes, l); |
| 1194 | memset(handshakeAuthKey->bytes, 0, 256 - l); |
| 1195 | } |
| 1196 |
| 1197 | BN_free(authKeyNum); |
| 1198 | BN_free(g_a); |
| 1199 | BN_free(b); |
| 1200 | BN_free(p); |
| 1201 |
| 1202 | uint32_t clientInnerDataSize = clientInnerData->getObjectSize(); |
| 1203 | uint32_t additionalSize = (clientInnerDataSize + SHA_DIGEST_LENGTH) % 16; |
| 1204 | if (additionalSize != 0) { |
| 1205 | additionalSize = 16 - additionalSize; |
| 1206 | } |
| 1207 | NativeByteBuffer *clientInnerDataBuffer = BuffersStorage::getInstance().getFreeBuffer(clientInnerDataSize + additionalSize + SHA_DIGEST_LENGTH); |
| 1208 | clientInnerDataBuffer->position(SHA_DIGEST_LENGTH); |
| 1209 | clientInnerData->serializeToStream(clientInnerDataBuffer); |
| 1210 | delete clientInnerData; |
| 1211 |
| 1212 | SHA1(clientInnerDataBuffer->bytes() + SHA_DIGEST_LENGTH, clientInnerDataSize, clientInnerDataBuffer->bytes()); |
| 1213 |
| 1214 | if (additionalSize != 0) { |
| 1215 | RAND_bytes(clientInnerDataBuffer->bytes() + SHA_DIGEST_LENGTH + clientInnerDataSize, additionalSize); |
| 1216 | } |
| 1217 |
| 1218 | TL_set_client_DH_params *setClientDhParams = new TL_set_client_DH_params(); |
| 1219 | setClientDhParams->nonce = std::unique_ptr<ByteArray>(new ByteArray(authNonce)); |
| 1220 | setClientDhParams->server_nonce = std::unique_ptr<ByteArray>(new ByteArray(authServerNonce)); |
| 1221 | aesIgeEncryption(clientInnerDataBuffer->bytes(), tmpAesKeyAndIv->bytes(), tmpAesKeyAndIv->bytes() + 32, true, false, clientInnerDataBuffer->limit()); |
| 1222 | setClientDhParams->encrypted_data = std::unique_ptr<ByteArray>(new ByteArray(clientInnerDataBuffer->bytes(), clientInnerDataBuffer->limit())); |
| 1223 | clientInnerDataBuffer->reuse(); |
| 1224 | tmpAesKeyAndIv->reuse(); |
| 1225 |
| 1226 | sendAckRequest(messageId); |
| 1227 | sendRequestData(setClientDhParams, true); |
| 1228 |
| 1229 | int32_t currentTime = (int32_t) (ConnectionsManager::getInstance().getCurrentTimeMillis() / 1000); |
| 1230 | timeDifference = dhInnerData->server_time - currentTime; |
| 1231 |
| 1232 | handshakeServerSalt = new TL_future_salt(); |
| 1233 | handshakeServerSalt->valid_since = currentTime + timeDifference - 5; |
| 1234 | handshakeServerSalt->valid_until = handshakeServerSalt->valid_since + 30 * 60; |
| 1235 | for (int32_t a = 7; a >= 0; a--) { |
| 1236 | handshakeServerSalt->salt <<= 8; |
| 1237 | handshakeServerSalt->salt |= (authNewNonce->bytes[a] ^ authServerNonce->bytes[a]); |
| 1238 | } |
| 1239 | } else { |
| 1240 | DEBUG_E("dc%u handshake: can't set DH params", datacenterId); |
| 1241 | beginHandshake(false); |
| 1242 | } |
| 1243 | } else if (dynamic_cast<Set_client_DH_params_answer *>(message)) { |
| 1244 | if (handshakeState != 3) { |
| 1245 | sendAckRequest(messageId); |
| 1246 | return; |
| 1247 | } |
| 1248 |
| 1249 | handshakeState = 4; |
| 1250 |
| 1251 | Set_client_DH_params_answer *result = (Set_client_DH_params_answer *) message; |
| 1252 |
| 1253 | if (!authNonce->isEqualTo(result->nonce.get())) { |
| 1254 | DEBUG_E("dc%u handshake: invalid DH answer nonce", datacenterId); |
| 1255 | beginHandshake(false); |
| 1256 | return; |
| 1257 | } |
| 1258 | if (!authServerNonce->isEqualTo(result->server_nonce.get())) { |
| 1259 | DEBUG_E("dc%u handshake: invalid DH answer server nonce", datacenterId); |
| 1260 | beginHandshake(false); |
| 1261 | return; |
| 1262 | } |
| 1263 |
| 1264 | sendAckRequest(messageId); |
| 1265 |
| 1266 | uint32_t authKeyAuxHashLength = authNewNonce->length + SHA_DIGEST_LENGTH + 1; |
| 1267 | NativeByteBuffer *authKeyAuxHashBuffer = BuffersStorage::getInstance().getFreeBuffer(authKeyAuxHashLength + SHA_DIGEST_LENGTH); |
| 1268 | authKeyAuxHashBuffer->writeBytes(authNewNonce); |
| 1269 | SHA1(handshakeAuthKey->bytes, handshakeAuthKey->length, authKeyAuxHashBuffer->bytes() + authNewNonce->length + 1); |
| 1270 |
| 1271 | if (typeInfo == typeid(TL_dh_gen_ok)) { |
| 1272 | authKeyAuxHashBuffer->writeByte(1); |
| 1273 | SHA1(authKeyAuxHashBuffer->bytes(), authKeyAuxHashLength - 12, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength); |
| 1274 |
| 1275 | if (memcmp(result->new_nonce_hash1->bytes, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength + SHA_DIGEST_LENGTH - 16, 16)) { |
| 1276 | DEBUG_E("dc%u handshake: invalid DH answer nonce hash 1", datacenterId); |
| 1277 | authKeyAuxHashBuffer->reuse(); |
| 1278 | beginHandshake(false); |
| 1279 | } else { |
| 1280 | DEBUG_D("dc%u handshake: completed, time difference = %d", datacenterId, timeDifference); |
| 1281 | authKey = handshakeAuthKey; |
| 1282 | handshakeAuthKey = nullptr; |
| 1283 | authKeyAuxHashBuffer->position(authNewNonce->length + 1 + 12); |
| 1284 | authKeyId = authKeyAuxHashBuffer->readInt64(nullptr); |
| 1285 | std::unique_ptr<TL_future_salt> salt = std::unique_ptr<TL_future_salt>(handshakeServerSalt); |
| 1286 | addServerSalt(salt); |
| 1287 | handshakeServerSalt = nullptr; |
| 1288 | ConnectionsManager::getInstance().onDatacenterHandshakeComplete(this, timeDifference); |
| 1289 | cleanupHandshake(); |
| 1290 | } |
| 1291 | authKeyAuxHashBuffer->reuse(); |
| 1292 | } else if (typeInfo == typeid(TL_dh_gen_retry)) { |
| 1293 | authKeyAuxHashBuffer->writeByte(2); |
| 1294 | SHA1(authKeyAuxHashBuffer->bytes(), authKeyAuxHashLength - 12, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength); |
| 1295 |
| 1296 | if (memcmp(result->new_nonce_hash2->bytes, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength + SHA_DIGEST_LENGTH - 16, 16)) { |
| 1297 | DEBUG_E("dc%u handshake: invalid DH answer nonce hash 2", datacenterId); |
| 1298 | beginHandshake(false); |
| 1299 | } else { |
| 1300 | DEBUG_D("dc%u handshake: retry DH", datacenterId); |
| 1301 | beginHandshake(false); |
| 1302 | } |
| 1303 | authKeyAuxHashBuffer->reuse(); |
| 1304 | } else if (typeInfo == typeid(TL_dh_gen_fail)) { |
| 1305 | authKeyAuxHashBuffer->writeByte(3); |
| 1306 | SHA1(authKeyAuxHashBuffer->bytes(), authKeyAuxHashLength - 12, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength); |
| 1307 |
| 1308 | if (memcmp(result->new_nonce_hash3->bytes, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength + SHA_DIGEST_LENGTH - 16, 16)) { |
| 1309 | DEBUG_E("dc%u handshake: invalid DH answer nonce hash 3", datacenterId); |
| 1310 | beginHandshake(false); |
| 1311 | } else { |
| 1312 | DEBUG_E("dc%u handshake: server declined DH params", datacenterId); |
| 1313 | beginHandshake(false); |
| 1314 | } |
| 1315 | authKeyAuxHashBuffer->reuse(); |
| 1316 | } |
| 1317 | } |
| 1318 | } |
| 1319 |
| 1320 | TLObject *Datacenter::getCurrentHandshakeRequest() { |
| 1321 | return handshakeRequest; |
| 1322 | } |
| 1323 |
| 1324 | void Datacenter::sendAckRequest(int64_t messageId) { |
| 1325 | TL_msgs_ack *msgsAck = new TL_msgs_ack(); |
| 1326 | msgsAck->msg_ids.push_back(messageId); |
| 1327 | sendRequestData(msgsAck, false); |
| 1328 | } |
| 1329 |
| 1330 | inline void generateMessageKey(uint8_t *authKey, uint8_t *messageKey, uint8_t *result, bool incoming) { |
| 1331 | uint32_t x = incoming ? 8 : 0; |
| 1332 |
| 1333 | static uint8_t sha[68]; |
| 1334 |
| 1335 | memcpy(sha + 20, messageKey, 16); |
| 1336 | memcpy(sha + 20 + 16, authKey + x, 32); |
| 1337 | SHA1(sha + 20, 48, sha); |
| 1338 | memcpy(result, sha, 8); |
| 1339 | memcpy(result + 32, sha + 8, 12); |
| 1340 |
| 1341 | memcpy(sha + 20, authKey + 32 + x, 16); |
| 1342 | memcpy(sha + 20 + 16, messageKey, 16); |
| 1343 | memcpy(sha + 20 + 16 + 16, authKey + 48 + x, 16); |
| 1344 | SHA1(sha + 20, 48, sha); |
| 1345 | memcpy(result + 8, sha + 8, 12); |
| 1346 | memcpy(result + 32 + 12, sha, 8); |
| 1347 |
| 1348 | memcpy(sha + 20, authKey + 64 + x, 32); |
| 1349 | memcpy(sha + 20 + 32, messageKey, 16); |
| 1350 | SHA1(sha + 20, 48, sha); |
| 1351 | memcpy(result + 8 + 12, sha + 4, 12); |
| 1352 | memcpy(result + 32 + 12 + 8, sha + 16, 4); |
| 1353 |
| 1354 | memcpy(sha + 20, messageKey, 16); |
| 1355 | memcpy(sha + 20 + 16, authKey + 96 + x, 32); |
| 1356 | SHA1(sha + 20, 48, sha); |
| 1357 | memcpy(result + 32 + 12 + 8 + 4, sha, 8); |
| 1358 | } |
| 1359 |
| 1360 | NativeByteBuffer *Datacenter::createRequestsData(std::vector<std::unique_ptr<NetworkMessage>> &requests, int32_t *quickAckId, Connection *connection) { |
| 1361 | if (authKey == nullptr || connection == nullptr) { |
| 1362 | return nullptr; |
| 1363 | } |
| 1364 |
| 1365 | int64_t messageId; |
| 1366 | TLObject *messageBody; |
| 1367 | bool freeMessageBody = false; |
| 1368 | int32_t messageSeqNo; |
| 1369 |
| 1370 | if (requests.size() == 1) { |
| 1371 | NetworkMessage *networkMessage = requests[0].get(); |
| 1372 |
| 1373 | if (networkMessage->message->outgoingBody != nullptr) { |
| 1374 | messageBody = networkMessage->message->outgoingBody; |
| 1375 | } else { |
| 1376 | messageBody = networkMessage->message->body.get(); |
| 1377 | } |
| 1378 | DEBUG_D("connection(%p, dc%u, type %d) send message (session: 0x%llx, seqno: %d, messageid: 0x%llx): %s(%p)", connection, datacenterId, connection->getConnectionType(), (uint64_t) connection->getSissionId(), networkMessage->message->seqno, (uint64_t) networkMessage->message->msg_id, typeid(*messageBody).name(), messageBody); |
| 1379 |
| 1380 | int64_t messageTime = (int64_t) (networkMessage->message->msg_id / 4294967296.0 * 1000); |
| 1381 | int64_t currentTime = ConnectionsManager::getInstance().getCurrentTimeMillis() + (int64_t) timeDifference * 1000; |
| 1382 |
| 1383 | if (messageTime < currentTime - 30000 || messageTime > currentTime + 25000) { |
| 1384 | DEBUG_D("wrap message in container"); |
| 1385 | TL_msg_container *messageContainer = new TL_msg_container(); |
| 1386 | messageContainer->messages.push_back(std::move(networkMessage->message)); |
| 1387 |
| 1388 | messageId = ConnectionsManager::getInstance().generateMessageId(); |
| 1389 | messageBody = messageContainer; |
| 1390 | messageSeqNo = connection->generateMessageSeqNo(false); |
| 1391 | freeMessageBody = true; |
| 1392 | } else { |
| 1393 | messageId = networkMessage->message->msg_id; |
| 1394 | messageSeqNo = networkMessage->message->seqno; |
| 1395 | } |
| 1396 | } else { |
| 1397 | DEBUG_D("start write messages to container"); |
| 1398 | TL_msg_container *messageContainer = new TL_msg_container(); |
| 1399 | size_t count = requests.size(); |
| 1400 | for (uint32_t a = 0; a < count; a++) { |
| 1401 | NetworkMessage *networkMessage = requests[a].get(); |
| 1402 | if (networkMessage->message->outgoingBody != nullptr) { |
| 1403 | messageBody = networkMessage->message->outgoingBody; |
| 1404 | } else { |
| 1405 | messageBody = networkMessage->message->body.get(); |
| 1406 | } |
| 1407 | DEBUG_D("connection(%p, dc%u, type %d) send message (session: 0x%llx, seqno: %d, messageid: 0x%llx): %s(%p)", connection, datacenterId, connection->getConnectionType(), (uint64_t) connection->getSissionId(), networkMessage->message->seqno, (uint64_t) networkMessage->message->msg_id, typeid(*messageBody).name(), messageBody); |
| 1408 | messageContainer->messages.push_back(std::unique_ptr<TL_message>(std::move(networkMessage->message))); |
| 1409 | } |
| 1410 | messageId = ConnectionsManager::getInstance().generateMessageId(); |
| 1411 | messageBody = messageContainer; |
| 1412 | freeMessageBody = true; |
| 1413 | messageSeqNo = connection->generateMessageSeqNo(false); |
| 1414 | } |
| 1415 |
| 1416 | uint32_t messageSize = messageBody->getObjectSize(); |
| 1417 | uint32_t additionalSize = (32 + messageSize) % 16; |
| 1418 | if (additionalSize != 0) { |
| 1419 | additionalSize = 16 - additionalSize; |
| 1420 | } |
| 1421 | NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(24 + 32 + messageSize + additionalSize); |
| 1422 | buffer->writeInt64(authKeyId); |
| 1423 | buffer->position(24); |
| 1424 |
| 1425 | int64_t serverSalt = getServerSalt(); |
| 1426 | buffer->writeInt64(serverSalt); |
| 1427 | buffer->writeInt64(connection->getSissionId()); |
| 1428 | buffer->writeInt64(messageId); |
| 1429 | buffer->writeInt32(messageSeqNo); |
| 1430 | buffer->writeInt32(messageSize); |
| 1431 | messageBody->serializeToStream(buffer); |
| 1432 | if (freeMessageBody) { |
| 1433 | delete messageBody; |
| 1434 | } |
| 1435 |
| 1436 | if (additionalSize != 0) { |
| 1437 | RAND_bytes(buffer->bytes() + 24 + 32 + messageSize, additionalSize); |
| 1438 | } |
| 1439 | static uint8_t messageKey[84]; |
| 1440 | SHA1(buffer->bytes() + 24, 32 + messageSize, messageKey); |
| 1441 | memcpy(buffer->bytes() + 8, messageKey + 4, 16); |
| 1442 |
| 1443 | if (quickAckId != nullptr) { |
| 1444 | *quickAckId = (((messageKey[0] & 0xff)) | |
| 1445 | ((messageKey[1] & 0xff) << 8) | |
| 1446 | ((messageKey[2] & 0xff) << 16) | |
| 1447 | ((messageKey[3] & 0xff) << 24)) & 0x7fffffff; |
| 1448 | } |
| 1449 |
| 1450 | generateMessageKey(authKey->bytes, messageKey + 4, messageKey + 20, false); |
| 1451 | aesIgeEncryption(buffer->bytes() + 24, messageKey + 20, messageKey + 52, true, false, buffer->limit() - 24); |
| 1452 |
| 1453 | return buffer; |
| 1454 | } |
| 1455 |
| 1456 | bool Datacenter::decryptServerResponse(int64_t keyId, uint8_t *key, uint8_t *data, uint32_t length) { |
| 1457 | if (authKeyId != keyId || length % 16 != 0) { |
| 1458 | return false; |
| 1459 | } |
| 1460 | static uint8_t messageKey[84]; |
| 1461 | generateMessageKey(authKey->bytes, key, messageKey + 20, true); |
| 1462 | aesIgeEncryption(data, messageKey + 20, messageKey + 52, false, false, length); |
| 1463 |
| 1464 | uint32_t messageLength; |
| 1465 | memcpy(&messageLength, data + 28, sizeof(uint32_t)); |
| 1466 | if (messageLength > length - 32) { |
| 1467 | return false; |
| 1468 | } |
| 1469 | messageLength += 32; |
| 1470 | if (messageLength > length) { |
| 1471 | messageLength = length; |
| 1472 | } |
| 1473 |
| 1474 | SHA1(data, messageLength, messageKey); |
| 1475 |
| 1476 | return memcmp(messageKey + 4, key, 16) == 0; |
| 1477 | } |
| 1478 |
| 1479 | bool Datacenter::hasAuthKey() { |
| 1480 | return authKey != nullptr; |
| 1481 | } |
| 1482 |
| 1483 | Connection *Datacenter::createConnectionByType(uint32_t connectionType) { |
| 1484 | uint32_t connectionNum = connectionType >> 16; |
| 1485 | connectionType = connectionType & 0x0000ffff; |
| 1486 | switch (connectionType) { |
| 1487 | case ConnectionTypeGeneric: |
| 1488 | return createGenericConnection(); |
| 1489 | case ConnectionTypeDownload: |
| 1490 | return createDownloadConnection(connectionNum); |
| 1491 | case ConnectionTypeUpload: |
| 1492 | return createUploadConnection(); |
| 1493 | case ConnectionTypePush: |
| 1494 | return createPushConnection(); |
| 1495 | default: |
| 1496 | return nullptr; |
| 1497 | } |
| 1498 | } |
| 1499 |
| 1500 | Connection *Datacenter::getDownloadConnection(uint32_t num, bool create) { |
| 1501 | if (authKey == nullptr) { |
| 1502 | return nullptr; |
| 1503 | } |
| 1504 | if (create) { |
| 1505 | createDownloadConnection(num)->connect(); |
| 1506 | } |
| 1507 | return downloadConnections[num]; |
| 1508 | } |
| 1509 |
| 1510 | Connection *Datacenter::getUploadConnection(bool create) { |
| 1511 | if (authKey == nullptr) { |
| 1512 | return nullptr; |
| 1513 | } |
| 1514 | if (create) { |
| 1515 | createUploadConnection()->connect(); |
| 1516 | } |
| 1517 | return uploadConnection; |
| 1518 | } |
| 1519 |
| 1520 | Connection *Datacenter::getGenericConnection(bool create) { |
| 1521 | if (authKey == nullptr) { |
| 1522 | return nullptr; |
| 1523 | } |
| 1524 | if (create) { |
| 1525 | createGenericConnection()->connect(); |
| 1526 | } |
| 1527 | return genericConnection; |
| 1528 | } |
| 1529 |
| 1530 | Connection *Datacenter::getPushConnection(bool create) { |
| 1531 | if (authKey == nullptr) { |
| 1532 | return nullptr; |
| 1533 | } |
| 1534 | if (create) { |
| 1535 | createPushConnection()->connect(); |
| 1536 | } |
| 1537 | return pushConnection; |
| 1538 | } |
| 1539 |
| 1540 | Connection *Datacenter::getConnectionByType(uint32_t connectionType, bool create) { |
| 1541 | uint32_t connectionNum = connectionType >> 16; |
| 1542 | connectionType = connectionType & 0x0000ffff; |
| 1543 | switch (connectionType) { |
| 1544 | case ConnectionTypeGeneric: |
| 1545 | return getGenericConnection(create); |
| 1546 | case ConnectionTypeDownload: |
| 1547 | return getDownloadConnection(connectionNum, create); |
| 1548 | case ConnectionTypeUpload: |
| 1549 | return getUploadConnection(create); |
| 1550 | case ConnectionTypePush: |
| 1551 | return getPushConnection(create); |
| 1552 | default: |
| 1553 | return nullptr; |
| 1554 | } |
| 1555 | } |
| 1556 |
| 1557 | void Datacenter::exportAuthorization() { |
| 1558 | if (exportingAuthorization) { |
| 1559 | return; |
| 1560 | } |
| 1561 | exportingAuthorization = true; |
| 1562 | TL_auth_exportAuthorization *request = new TL_auth_exportAuthorization(); |
| 1563 | request->dc_id = datacenterId; |
| 1564 | DEBUG_D("dc%u begin export authorization", datacenterId); |
| 1565 | ConnectionsManager::getInstance().sendRequest(request, [&](TLObject *response, TL_error *error) { |
| 1566 | if (error == nullptr) { |
| 1567 | TL_auth_exportedAuthorization *res = (TL_auth_exportedAuthorization *) response; |
| 1568 | TL_auth_importAuthorization *request2 = new TL_auth_importAuthorization(); |
| 1569 | request2->bytes = std::move(res->bytes); |
| 1570 | request2->id = res->id; |
| 1571 | DEBUG_D("dc%u begin import authorization", datacenterId); |
| 1572 | ConnectionsManager::getInstance().sendRequest(request2, [&](TLObject *response2, TL_error *error2) { |
| 1573 | if (error2 == nullptr) { |
| 1574 | authorized = true; |
| 1575 | ConnectionsManager::getInstance().onDatacenterExportAuthorizationComplete(this); |
| 1576 | } else { |
| 1577 | DEBUG_D("dc%u failed import authorization", datacenterId); |
| 1578 | } |
| 1579 | exportingAuthorization = false; |
| 1580 | }, nullptr, RequestFlagEnableUnauthorized | RequestFlagWithoutLogin, datacenterId, ConnectionTypeGeneric, true); |
| 1581 | } else { |
| 1582 | DEBUG_D("dc%u failed export authorization", datacenterId); |
| 1583 | exportingAuthorization = false; |
| 1584 | } |
| 1585 | }, nullptr, 0, DEFAULT_DATACENTER_ID, ConnectionTypeGeneric, true); |
| 1586 | } |
| 1587 |
| 1588 | bool Datacenter::isExportingAuthorization() { |
| 1589 | return exportingAuthorization; |
| 1590 | } |
| 1591 |