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