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