special_config_request.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. /*
  2. This file is part of Telegram Desktop,
  3. the official desktop application for the Telegram messaging service.
  4. For license and copyright information please follow this link:
  5. https://github.com/telegramdesktop/tdesktop/blob/master/LEGAL
  6. */
  7. #include "mtproto/special_config_request.h"
  8. #include "mtproto/details/mtproto_rsa_public_key.h"
  9. #include "mtproto/mtproto_dc_options.h"
  10. #include "mtproto/mtproto_auth_key.h"
  11. #include "base/unixtime.h"
  12. #include "base/openssl_help.h"
  13. #include "base/call_delayed.h"
  14. #include <QtCore/QJsonDocument>
  15. #include <QtCore/QJsonArray>
  16. #include <QtCore/QJsonObject>
  17. namespace MTP::details {
  18. namespace {
  19. constexpr auto kSendNextTimeout = crl::time(800);
  20. constexpr auto kPublicKey = "\
  21. -----BEGIN RSA PUBLIC KEY-----\n\
  22. MIIBCgKCAQEAyr+18Rex2ohtVy8sroGPBwXD3DOoKCSpjDqYoXgCqB7ioln4eDCF\n\
  23. fOBUlfXUEvM/fnKCpF46VkAftlb4VuPDeQSS/ZxZYEGqHaywlroVnXHIjgqoxiAd\n\
  24. 192xRGreuXIaUKmkwlM9JID9WS2jUsTpzQ91L8MEPLJ/4zrBwZua8W5fECwCCh2c\n\
  25. 9G5IzzBm+otMS/YKwmR1olzRCyEkyAEjXWqBI9Ftv5eG8m0VkBzOG655WIYdyV0H\n\
  26. fDK/NWcvGqa0w/nriMD6mDjKOryamw0OP9QuYgMN0C9xMW9y8SmP4h92OAWodTYg\n\
  27. Y1hZCxdv6cs5UnW9+PWvS+WIbkh+GaWYxwIDAQAB\n\
  28. -----END RSA PUBLIC KEY-----\
  29. "_cs;
  30. const auto kRemoteProject = "peak-vista-421";
  31. const auto kFireProject = "reserve-5a846";
  32. const auto kConfigKey = "ipconfig";
  33. const auto kConfigSubKey = "v3";
  34. const auto kApiKey = "AIzaSyC2-kAkpDsroixRXw-sTw-Wfqo4NxjMwwM";
  35. const auto kAppId = "1:560508485281:web:4ee13a6af4e84d49e67ae0";
  36. QString ApiDomain(const QString &service) {
  37. return service + ".googleapis.com";
  38. }
  39. QString GenerateInstanceId() {
  40. auto fid = bytes::array<17>();
  41. bytes::set_random(fid);
  42. fid[0] = (bytes::type(0xF0) & fid[0]) | bytes::type(0x07);
  43. return QString::fromLatin1(
  44. QByteArray::fromRawData(
  45. reinterpret_cast<const char*>(fid.data()),
  46. fid.size()
  47. ).toBase64(QByteArray::Base64UrlEncoding).mid(0, 22));
  48. }
  49. QString InstanceId() {
  50. static const auto result = GenerateInstanceId();
  51. return result;
  52. }
  53. bool CheckPhoneByPrefixesRules(const QString &phone, const QString &rules) {
  54. static const auto RegExp = QRegularExpression("[^0-9]");
  55. const auto check = QString(phone).replace(
  56. RegExp,
  57. QString());
  58. auto result = false;
  59. for (const auto &prefix : rules.split(',')) {
  60. if (prefix.isEmpty()) {
  61. result = true;
  62. } else if (prefix[0] == '+' && check.startsWith(prefix.mid(1))) {
  63. result = true;
  64. } else if (prefix[0] == '-' && check.startsWith(prefix.mid(1))) {
  65. return false;
  66. }
  67. }
  68. return result;
  69. }
  70. QByteArray ConcatenateDnsTxtFields(const std::vector<DnsEntry> &response) {
  71. auto entries = QMultiMap<int, QString>();
  72. for (const auto &entry : response) {
  73. entries.insert(INT_MAX - entry.data.size(), entry.data);
  74. }
  75. return QStringList(entries.values()).join(QString()).toLatin1();
  76. }
  77. QByteArray ParseRemoteConfigResponse(const QByteArray &bytes) {
  78. auto error = QJsonParseError{ 0, QJsonParseError::NoError };
  79. const auto document = QJsonDocument::fromJson(bytes, &error);
  80. if (error.error != QJsonParseError::NoError) {
  81. LOG(("Config Error: Failed to parse fire response JSON, error: %1"
  82. ).arg(error.errorString()));
  83. return {};
  84. } else if (!document.isObject()) {
  85. LOG(("Config Error: Not an object received in fire response JSON."));
  86. return {};
  87. }
  88. return document.object().value(
  89. "entries"
  90. ).toObject().value(
  91. u"%1%2"_q.arg(kConfigKey, kConfigSubKey)
  92. ).toString().toLatin1();
  93. }
  94. QByteArray ParseFireStoreResponse(const QByteArray &bytes) {
  95. auto error = QJsonParseError{ 0, QJsonParseError::NoError };
  96. const auto document = QJsonDocument::fromJson(bytes, &error);
  97. if (error.error != QJsonParseError::NoError) {
  98. LOG(("Config Error: Failed to parse fire response JSON, error: %1"
  99. ).arg(error.errorString()));
  100. return {};
  101. } else if (!document.isObject()) {
  102. LOG(("Config Error: Not an object received in fire response JSON."));
  103. return {};
  104. }
  105. return document.object().value(
  106. "fields"
  107. ).toObject().value(
  108. "data"
  109. ).toObject().value(
  110. "stringValue"
  111. ).toString().toLatin1();
  112. }
  113. QByteArray ParseRealtimeResponse(const QByteArray &bytes) {
  114. if (bytes.size() < 2
  115. || bytes[0] != '"'
  116. || bytes[bytes.size() - 1] != '"') {
  117. return QByteArray();
  118. }
  119. return bytes.mid(1, bytes.size() - 2);
  120. }
  121. [[nodiscard]] QDateTime ParseHttpDate(const QString &date) {
  122. // Wed, 10 Jul 2019 14:33:38 GMT
  123. static const auto expression = QRegularExpression(
  124. R"(\w\w\w, (\d\d) (\w\w\w) (\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT)");
  125. const auto match = expression.match(date);
  126. if (!match.hasMatch()) {
  127. return QDateTime();
  128. }
  129. const auto number = [&](int index) {
  130. return match.capturedView(index).toInt();
  131. };
  132. const auto day = number(1);
  133. const auto month = [&] {
  134. static const auto months = {
  135. "Jan",
  136. "Feb",
  137. "Mar",
  138. "Apr",
  139. "May",
  140. "Jun",
  141. "Jul",
  142. "Aug",
  143. "Sep",
  144. "Oct",
  145. "Nov",
  146. "Dec"
  147. };
  148. const auto captured = match.capturedView(2);
  149. for (auto i = begin(months); i != end(months); ++i) {
  150. if (captured == QString(*i)) {
  151. return 1 + int(i - begin(months));
  152. }
  153. }
  154. return 0;
  155. }();
  156. const auto year = number(3);
  157. const auto hour = number(4);
  158. const auto minute = number(5);
  159. const auto second = number(6);
  160. return QDateTime(
  161. QDate(year, month, day),
  162. QTime(hour, minute, second),
  163. Qt::UTC);
  164. }
  165. } // namespace
  166. SpecialConfigRequest::SpecialConfigRequest(
  167. Fn<void(
  168. DcId dcId,
  169. const std::string &ip,
  170. int port,
  171. bytes::const_span secret)> callback,
  172. Fn<void()> timeDoneCallback,
  173. bool isTestMode,
  174. const QString &domainString,
  175. const QString &phone)
  176. : _callback(std::move(callback))
  177. , _timeDoneCallback(std::move(timeDoneCallback))
  178. , _domainString(domainString)
  179. , _phone(phone) {
  180. Expects((_callback == nullptr) != (_timeDoneCallback == nullptr));
  181. _manager.setProxy(QNetworkProxy::NoProxy);
  182. std::random_device rd;
  183. const auto shuffle = [&](int from, int till) {
  184. Expects(till > from);
  185. ranges::shuffle(
  186. begin(_attempts) + from,
  187. begin(_attempts) + till,
  188. std::mt19937(rd()));
  189. };
  190. _attempts = {};
  191. _attempts.push_back({ Type::Google, "dns.google.com" });
  192. _attempts.push_back({ Type::Mozilla, "mozilla.cloudflare-dns.com" });
  193. _attempts.push_back({ Type::RemoteConfig, "firebaseremoteconfig" });
  194. if (!_timeDoneCallback) {
  195. _attempts.push_back({ Type::FireStore, "firestore" });
  196. for (const auto &domain : DnsDomains()) {
  197. _attempts.push_back({ Type::FireStore, domain, "firestore" });
  198. }
  199. }
  200. shuffle(0, 2);
  201. if (!_timeDoneCallback) {
  202. shuffle(_attempts.size() - (int(DnsDomains().size()) + 1), _attempts.size());
  203. }
  204. if (isTestMode) {
  205. _attempts.erase(ranges::remove_if(_attempts, [](
  206. const Attempt &attempt) {
  207. return (attempt.type != Type::Google)
  208. && (attempt.type != Type::Mozilla);
  209. }), _attempts.end());
  210. }
  211. ranges::reverse(_attempts); // We go from last to first.
  212. sendNextRequest();
  213. }
  214. SpecialConfigRequest::SpecialConfigRequest(
  215. Fn<void(
  216. DcId dcId,
  217. const std::string &ip,
  218. int port,
  219. bytes::const_span secret)> callback,
  220. bool isTestMode,
  221. const QString &domainString,
  222. const QString &phone)
  223. : SpecialConfigRequest(
  224. std::move(callback),
  225. nullptr,
  226. isTestMode,
  227. domainString,
  228. phone) {
  229. }
  230. SpecialConfigRequest::SpecialConfigRequest(
  231. Fn<void()> timeDoneCallback,
  232. bool isTestMode,
  233. const QString &domainString)
  234. : SpecialConfigRequest(
  235. nullptr,
  236. std::move(timeDoneCallback),
  237. isTestMode,
  238. domainString,
  239. QString()) {
  240. }
  241. void SpecialConfigRequest::sendNextRequest() {
  242. Expects(!_attempts.empty());
  243. const auto attempt = _attempts.back();
  244. _attempts.pop_back();
  245. if (!_attempts.empty()) {
  246. base::call_delayed(kSendNextTimeout, this, [=] {
  247. sendNextRequest();
  248. });
  249. }
  250. performRequest(attempt);
  251. }
  252. void SpecialConfigRequest::performRequest(const Attempt &attempt) {
  253. const auto type = attempt.type;
  254. auto url = QUrl();
  255. url.setScheme(u"https"_q);
  256. auto request = QNetworkRequest();
  257. auto payload = QByteArray();
  258. switch (type) {
  259. case Type::Mozilla: {
  260. url.setHost(attempt.data);
  261. url.setPath(u"/dns-query"_q);
  262. url.setQuery(u"name=%1&type=16&random_padding=%2"_q.arg(
  263. _domainString,
  264. GenerateDnsRandomPadding()));
  265. request.setRawHeader("accept", "application/dns-json");
  266. } break;
  267. case Type::Google: {
  268. url.setHost(attempt.data);
  269. url.setPath(u"/resolve"_q);
  270. url.setQuery(u"name=%1&type=ANY&random_padding=%2"_q.arg(
  271. _domainString,
  272. GenerateDnsRandomPadding()));
  273. if (!attempt.host.isEmpty()) {
  274. const auto host = attempt.host + ".google.com";
  275. request.setRawHeader("Host", host.toLatin1());
  276. }
  277. } break;
  278. case Type::RemoteConfig: {
  279. url.setHost(ApiDomain(attempt.data));
  280. url.setPath((u"/v1/projects/%1/namespaces/firebase:fetch"_q
  281. ).arg(kRemoteProject));
  282. url.setQuery(u"key=%1"_q.arg(kApiKey));
  283. payload = u"{\"app_id\":\"%1\",\"app_instance_id\":\"%2\"}"_q.arg(
  284. kAppId,
  285. InstanceId()).toLatin1();
  286. request.setRawHeader("Content-Type", "application/json");
  287. } break;
  288. case Type::Realtime: {
  289. url.setHost(kFireProject + u".%1"_q.arg(attempt.data));
  290. url.setPath(u"/%1%2.json"_q.arg(kConfigKey, kConfigSubKey));
  291. } break;
  292. case Type::FireStore: {
  293. url.setHost(attempt.host.isEmpty()
  294. ? ApiDomain(attempt.data)
  295. : attempt.data);
  296. url.setPath((u"/v1/projects/%1/databases/(default)/documents/%2/%3"_q
  297. ).arg(
  298. kFireProject,
  299. kConfigKey,
  300. kConfigSubKey));
  301. if (!attempt.host.isEmpty()) {
  302. const auto host = ApiDomain(attempt.host);
  303. request.setRawHeader("Host", host.toLatin1());
  304. }
  305. } break;
  306. default: Unexpected("Type in SpecialConfigRequest::performRequest.");
  307. }
  308. request.setUrl(url);
  309. request.setRawHeader("User-Agent", DnsUserAgent());
  310. const auto reply = _requests.emplace_back(payload.isEmpty()
  311. ? _manager.get(request)
  312. : _manager.post(request, payload)
  313. ).reply;
  314. connect(reply, &QNetworkReply::finished, this, [=] {
  315. requestFinished(type, reply);
  316. });
  317. }
  318. void SpecialConfigRequest::handleHeaderUnixtime(
  319. not_null<QNetworkReply*> reply) {
  320. if (reply->error() != QNetworkReply::NoError) {
  321. return;
  322. }
  323. const auto date = QString::fromLatin1([&] {
  324. for (const auto &pair : reply->rawHeaderPairs()) {
  325. if (pair.first == "Date") {
  326. return pair.second;
  327. }
  328. }
  329. return QByteArray();
  330. }());
  331. if (date.isEmpty()) {
  332. LOG(("Config Error: No 'Date' header received."));
  333. return;
  334. }
  335. const auto parsed = ParseHttpDate(date);
  336. if (!parsed.isValid()) {
  337. LOG(("Config Error: Bad 'Date' header received: %1").arg(date));
  338. return;
  339. }
  340. base::unixtime::http_update(parsed.toSecsSinceEpoch());
  341. if (_timeDoneCallback) {
  342. _timeDoneCallback();
  343. }
  344. }
  345. void SpecialConfigRequest::requestFinished(
  346. Type type,
  347. not_null<QNetworkReply*> reply) {
  348. handleHeaderUnixtime(reply);
  349. const auto result = finalizeRequest(reply);
  350. if (!_callback || result.isEmpty()) {
  351. return;
  352. }
  353. switch (type) {
  354. case Type::Mozilla:
  355. case Type::Google: {
  356. constexpr auto kTypeRestriction = 16; // TXT
  357. handleResponse(ConcatenateDnsTxtFields(
  358. ParseDnsResponse(result, kTypeRestriction)));
  359. } break;
  360. case Type::RemoteConfig: {
  361. handleResponse(ParseRemoteConfigResponse(result));
  362. } break;
  363. case Type::Realtime: {
  364. handleResponse(ParseRealtimeResponse(result));
  365. } break;
  366. case Type::FireStore: {
  367. handleResponse(ParseFireStoreResponse(result));
  368. } break;
  369. default: Unexpected("Type in SpecialConfigRequest::requestFinished.");
  370. }
  371. }
  372. QByteArray SpecialConfigRequest::finalizeRequest(
  373. not_null<QNetworkReply*> reply) {
  374. if (reply->error() != QNetworkReply::NoError) {
  375. DEBUG_LOG(("Config Error: Failed to get response, error: %2 (%3)"
  376. ).arg(reply->errorString()
  377. ).arg(reply->error()));
  378. }
  379. const auto result = reply->readAll();
  380. const auto from = ranges::remove(
  381. _requests,
  382. reply,
  383. [](const ServiceWebRequest &request) { return request.reply; });
  384. _requests.erase(from, end(_requests));
  385. return result;
  386. }
  387. bool SpecialConfigRequest::decryptSimpleConfig(const QByteArray &bytes) {
  388. auto cleanBytes = bytes;
  389. auto removeFrom = std::remove_if(cleanBytes.begin(), cleanBytes.end(), [](char ch) {
  390. auto isGoodBase64 = (ch == '+') || (ch == '=') || (ch == '/')
  391. || (ch >= 'a' && ch <= 'z')
  392. || (ch >= 'A' && ch <= 'Z')
  393. || (ch >= '0' && ch <= '9');
  394. return !isGoodBase64;
  395. });
  396. if (removeFrom != cleanBytes.end()) {
  397. cleanBytes.remove(removeFrom - cleanBytes.begin(), cleanBytes.end() - removeFrom);
  398. }
  399. constexpr auto kGoodSizeBase64 = 344;
  400. if (cleanBytes.size() != kGoodSizeBase64) {
  401. LOG(("Config Error: Bad data size %1 required %2").arg(cleanBytes.size()).arg(kGoodSizeBase64));
  402. return false;
  403. }
  404. constexpr auto kGoodSizeData = 256;
  405. auto decodedBytes = QByteArray::fromBase64(cleanBytes, QByteArray::Base64Encoding);
  406. if (decodedBytes.size() != kGoodSizeData) {
  407. LOG(("Config Error: Bad data size %1 required %2").arg(decodedBytes.size()).arg(kGoodSizeData));
  408. return false;
  409. }
  410. auto publicKey = details::RSAPublicKey(bytes::make_span(kPublicKey));
  411. auto decrypted = publicKey.decrypt(bytes::make_span(decodedBytes));
  412. auto decryptedBytes = gsl::make_span(decrypted);
  413. auto aesEncryptedBytes = decryptedBytes.subspan(CTRState::KeySize);
  414. auto aesivec = bytes::make_vector(decryptedBytes.subspan(CTRState::KeySize - CTRState::IvecSize, CTRState::IvecSize));
  415. AES_KEY aeskey;
  416. AES_set_decrypt_key(reinterpret_cast<const unsigned char*>(decryptedBytes.data()), CTRState::KeySize * CHAR_BIT, &aeskey);
  417. AES_cbc_encrypt(reinterpret_cast<const unsigned char*>(aesEncryptedBytes.data()), reinterpret_cast<unsigned char*>(aesEncryptedBytes.data()), aesEncryptedBytes.size(), &aeskey, reinterpret_cast<unsigned char*>(aesivec.data()), AES_DECRYPT);
  418. constexpr auto kDigestSize = 16;
  419. auto dataSize = aesEncryptedBytes.size() - kDigestSize;
  420. auto data = aesEncryptedBytes.subspan(0, dataSize);
  421. auto hash = openssl::Sha256(data);
  422. if (bytes::compare(gsl::make_span(hash).subspan(0, kDigestSize), aesEncryptedBytes.subspan(dataSize)) != 0) {
  423. LOG(("Config Error: Bad digest."));
  424. return false;
  425. }
  426. mtpBuffer buffer;
  427. buffer.resize(data.size() / sizeof(mtpPrime));
  428. bytes::copy(bytes::make_span(buffer), data);
  429. auto from = &*buffer.cbegin();
  430. auto end = from + buffer.size();
  431. auto realLength = *from++;
  432. if (realLength <= 0 || realLength > dataSize || (realLength & 0x03)) {
  433. LOG(("Config Error: Bad length %1.").arg(realLength));
  434. return false;
  435. }
  436. if (!_simpleConfig.read(from, end)) {
  437. LOG(("Config Error: Could not read configSimple."));
  438. return false;
  439. }
  440. if ((end - from) * sizeof(mtpPrime) != (dataSize - realLength)) {
  441. LOG(("Config Error: Bad read length %1, should be %2.").arg((end - from) * sizeof(mtpPrime)).arg(dataSize - realLength));
  442. return false;
  443. }
  444. return true;
  445. }
  446. void SpecialConfigRequest::handleResponse(const QByteArray &bytes) {
  447. if (!decryptSimpleConfig(bytes)) {
  448. return;
  449. }
  450. Assert(_simpleConfig.type() == mtpc_help_configSimple);
  451. const auto &config = _simpleConfig.c_help_configSimple();
  452. const auto now = base::unixtime::http_now();
  453. if (now > config.vexpires().v) {
  454. LOG(("Config Error: "
  455. "Bad date frame for simple config: %1-%2, our time is %3."
  456. ).arg(config.vdate().v
  457. ).arg(config.vexpires().v
  458. ).arg(now));
  459. return;
  460. }
  461. if (config.vrules().v.empty()) {
  462. LOG(("Config Error: Empty simple config received."));
  463. return;
  464. }
  465. for (const auto &rule : config.vrules().v) {
  466. Assert(rule.type() == mtpc_accessPointRule);
  467. const auto &data = rule.c_accessPointRule();
  468. const auto phoneRules = qs(data.vphone_prefix_rules());
  469. if (!CheckPhoneByPrefixesRules(_phone, phoneRules)) {
  470. continue;
  471. }
  472. const auto dcId = data.vdc_id().v;
  473. for (const auto &address : data.vips().v) {
  474. const auto parseIp = [](const MTPint &ipv4) {
  475. const auto ip = *reinterpret_cast<const uint32*>(&ipv4.v);
  476. return (u"%1.%2.%3.%4"_q
  477. ).arg((ip >> 24) & 0xFF
  478. ).arg((ip >> 16) & 0xFF
  479. ).arg((ip >> 8) & 0xFF
  480. ).arg(ip & 0xFF).toStdString();
  481. };
  482. switch (address.type()) {
  483. case mtpc_ipPort: {
  484. const auto &fields = address.c_ipPort();
  485. const auto ip = parseIp(fields.vipv4());
  486. if (!ip.empty()) {
  487. _callback(dcId, ip, fields.vport().v, {});
  488. }
  489. } break;
  490. case mtpc_ipPortSecret: {
  491. const auto &fields = address.c_ipPortSecret();
  492. const auto ip = parseIp(fields.vipv4());
  493. if (!ip.empty()) {
  494. _callback(
  495. dcId,
  496. ip,
  497. fields.vport().v,
  498. bytes::make_span(fields.vsecret().v));
  499. }
  500. } break;
  501. default: Unexpected("Type in simpleConfig ips.");
  502. }
  503. }
  504. }
  505. _callback(0, std::string(), 0, {});
  506. }
  507. } // namespace MTP::details