MadelineProto/src/danog/MadelineProto/SecretChats/AuthKeyHandler.php

336 lines
17 KiB
PHP
Raw Normal View History

<?php
Merge alpha into master (async, huge bugfixes and more) (#546) * Implement async and lots of bugfixes * Implement more async * Implement async, implement bugfixes for the connection module, for the datacenter module, huge bugfixes, huge perfomance improvements, media DCs for https, advanced selecting, custom var_dump, totally rewritten IOLoop and response mechanism, promises, improvements to the TL parser, custom mb_substr * Apply fixes from StyleCI * Bugfixes * Apply fixes from StyleCI * Bugfixes, implement combined promises * Apply fixes from StyleCI * Support passing method arguments as callable * Starting to write async upload logic * Apply fixes from StyleCI * Start implementing async file upload * Apply fixes from StyleCI * bugfix * Apply fixes from StyleCI * Start rewriting connection module * Add PHP file docblocks for all classes * Start working on new async stream API * Finish writing stream API * More stream API fixes * Apply fixes from StyleCI * Rewrite DataCenter and Connection modules * Clean up stream API documentation * Fixes * Apply fixes from StyleCI * Add referenced parameter to get length of buffer to read in getReadBuffer API * Moved all MessageHandler code in the Connection module, added a PHP version warning in the phar * Start fixing reads * Fix all protocol stream wrappers * Apply fixes from StyleCI * Implement disconnection, and remove end function * Working async RPC * Implement async file upload * Bugfix * Method recall bugfixes * Bugfixes * Trait bugfixes * Fix FIFO buffer * Bugfixes and speedtests * Async logging * Implement websocket streams * Implement loop API, signal API, clean closing and start changing layer * Small magna, websocket and HTTP fixes * Clean up loop API * Improved stack traces, 2FA and async * Login fixes * Added instructions for manual verification * Small fixes * More app info improvements * More app info improvements * TL and 2FA fixes * Update to layer 89 * More bugfixes * Implement broken media reporting * Remove debug comments * PHP 7.2 backwards compatibility * Bugfixes * Async key generation * Some simplifications * Transport fixes * Cleanup * async API * Performance fixes * Fixes to async API * Bugfixes * Implement one-time async loop * Authorization and logging fixes * Update to layer 91 * 7to5 fix * Null coalesce conversion * Implement socks5 proxy * Implement HTTP proxy * Fixes to HTTP proxy * MTProxy and socks5 fixes * Disable PHP 5 conversion * Proxies have higher priority * Avoid error handling in vendor * Override composer dependencies * Fix travis build * Final composer fixes * Proxy logic fixes * Fix get_updates update handling * Do not use parallel file driver if not supported * Refactor loader and implement HTTP fixes * Suppress errors in loader * HTTP and authorization fixes * HTTP fixes * Improved peer management * Use HTTP protocol on altervista * Small bugfixes * Minor fixes * Docufix * Docufix * Legacy fixes * Fix message queue * Avoid updating if using MTProxy * Improve logs and examples * Trim final newlines while converting parse mode * Reimplement noResponse flag * Async combined event handler and APIFactory fixes * Actually return config * Case-insensitive methods * Bugfix * Apply fixes from StyleCI (#545) * MTProxy fixes * PHP 5 warning * Improved PHP 5 warning * Use <br> along with newlines in web logs * Update docs
2018-12-26 20:51:14 +01:00
/**
* AuthKeyHandler module.
*
* This file is part of MadelineProto.
* MadelineProto is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
* MadelineProto is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU General Public License along with MadelineProto.
* If not, see <http://www.gnu.org/licenses/>.
*
* @author Daniil Gentili <daniil@daniil.it>
2020-02-17 14:13:46 +01:00
* @copyright 2016-2020 Daniil Gentili <daniil@daniil.it>
Merge alpha into master (async, huge bugfixes and more) (#546) * Implement async and lots of bugfixes * Implement more async * Implement async, implement bugfixes for the connection module, for the datacenter module, huge bugfixes, huge perfomance improvements, media DCs for https, advanced selecting, custom var_dump, totally rewritten IOLoop and response mechanism, promises, improvements to the TL parser, custom mb_substr * Apply fixes from StyleCI * Bugfixes * Apply fixes from StyleCI * Bugfixes, implement combined promises * Apply fixes from StyleCI * Support passing method arguments as callable * Starting to write async upload logic * Apply fixes from StyleCI * Start implementing async file upload * Apply fixes from StyleCI * bugfix * Apply fixes from StyleCI * Start rewriting connection module * Add PHP file docblocks for all classes * Start working on new async stream API * Finish writing stream API * More stream API fixes * Apply fixes from StyleCI * Rewrite DataCenter and Connection modules * Clean up stream API documentation * Fixes * Apply fixes from StyleCI * Add referenced parameter to get length of buffer to read in getReadBuffer API * Moved all MessageHandler code in the Connection module, added a PHP version warning in the phar * Start fixing reads * Fix all protocol stream wrappers * Apply fixes from StyleCI * Implement disconnection, and remove end function * Working async RPC * Implement async file upload * Bugfix * Method recall bugfixes * Bugfixes * Trait bugfixes * Fix FIFO buffer * Bugfixes and speedtests * Async logging * Implement websocket streams * Implement loop API, signal API, clean closing and start changing layer * Small magna, websocket and HTTP fixes * Clean up loop API * Improved stack traces, 2FA and async * Login fixes * Added instructions for manual verification * Small fixes * More app info improvements * More app info improvements * TL and 2FA fixes * Update to layer 89 * More bugfixes * Implement broken media reporting * Remove debug comments * PHP 7.2 backwards compatibility * Bugfixes * Async key generation * Some simplifications * Transport fixes * Cleanup * async API * Performance fixes * Fixes to async API * Bugfixes * Implement one-time async loop * Authorization and logging fixes * Update to layer 91 * 7to5 fix * Null coalesce conversion * Implement socks5 proxy * Implement HTTP proxy * Fixes to HTTP proxy * MTProxy and socks5 fixes * Disable PHP 5 conversion * Proxies have higher priority * Avoid error handling in vendor * Override composer dependencies * Fix travis build * Final composer fixes * Proxy logic fixes * Fix get_updates update handling * Do not use parallel file driver if not supported * Refactor loader and implement HTTP fixes * Suppress errors in loader * HTTP and authorization fixes * HTTP fixes * Improved peer management * Use HTTP protocol on altervista * Small bugfixes * Minor fixes * Docufix * Docufix * Legacy fixes * Fix message queue * Avoid updating if using MTProxy * Improve logs and examples * Trim final newlines while converting parse mode * Reimplement noResponse flag * Async combined event handler and APIFactory fixes * Actually return config * Case-insensitive methods * Bugfix * Apply fixes from StyleCI (#545) * MTProxy fixes * PHP 5 warning * Improved PHP 5 warning * Use <br> along with newlines in web logs * Update docs
2018-12-26 20:51:14 +01:00
* @license https://opensource.org/licenses/AGPL-3.0 AGPLv3
*
2019-10-31 15:07:35 +01:00
* @link https://docs.madelineproto.xyz MadelineProto documentation
Merge alpha into master (async, huge bugfixes and more) (#546) * Implement async and lots of bugfixes * Implement more async * Implement async, implement bugfixes for the connection module, for the datacenter module, huge bugfixes, huge perfomance improvements, media DCs for https, advanced selecting, custom var_dump, totally rewritten IOLoop and response mechanism, promises, improvements to the TL parser, custom mb_substr * Apply fixes from StyleCI * Bugfixes * Apply fixes from StyleCI * Bugfixes, implement combined promises * Apply fixes from StyleCI * Support passing method arguments as callable * Starting to write async upload logic * Apply fixes from StyleCI * Start implementing async file upload * Apply fixes from StyleCI * bugfix * Apply fixes from StyleCI * Start rewriting connection module * Add PHP file docblocks for all classes * Start working on new async stream API * Finish writing stream API * More stream API fixes * Apply fixes from StyleCI * Rewrite DataCenter and Connection modules * Clean up stream API documentation * Fixes * Apply fixes from StyleCI * Add referenced parameter to get length of buffer to read in getReadBuffer API * Moved all MessageHandler code in the Connection module, added a PHP version warning in the phar * Start fixing reads * Fix all protocol stream wrappers * Apply fixes from StyleCI * Implement disconnection, and remove end function * Working async RPC * Implement async file upload * Bugfix * Method recall bugfixes * Bugfixes * Trait bugfixes * Fix FIFO buffer * Bugfixes and speedtests * Async logging * Implement websocket streams * Implement loop API, signal API, clean closing and start changing layer * Small magna, websocket and HTTP fixes * Clean up loop API * Improved stack traces, 2FA and async * Login fixes * Added instructions for manual verification * Small fixes * More app info improvements * More app info improvements * TL and 2FA fixes * Update to layer 89 * More bugfixes * Implement broken media reporting * Remove debug comments * PHP 7.2 backwards compatibility * Bugfixes * Async key generation * Some simplifications * Transport fixes * Cleanup * async API * Performance fixes * Fixes to async API * Bugfixes * Implement one-time async loop * Authorization and logging fixes * Update to layer 91 * 7to5 fix * Null coalesce conversion * Implement socks5 proxy * Implement HTTP proxy * Fixes to HTTP proxy * MTProxy and socks5 fixes * Disable PHP 5 conversion * Proxies have higher priority * Avoid error handling in vendor * Override composer dependencies * Fix travis build * Final composer fixes * Proxy logic fixes * Fix get_updates update handling * Do not use parallel file driver if not supported * Refactor loader and implement HTTP fixes * Suppress errors in loader * HTTP and authorization fixes * HTTP fixes * Improved peer management * Use HTTP protocol on altervista * Small bugfixes * Minor fixes * Docufix * Docufix * Legacy fixes * Fix message queue * Avoid updating if using MTProxy * Improve logs and examples * Trim final newlines while converting parse mode * Reimplement noResponse flag * Async combined event handler and APIFactory fixes * Actually return config * Case-insensitive methods * Bugfix * Apply fixes from StyleCI (#545) * MTProxy fixes * PHP 5 warning * Improved PHP 5 warning * Use <br> along with newlines in web logs * Update docs
2018-12-26 20:51:14 +01:00
*/
2018-02-24 17:54:39 +01:00
namespace danog\MadelineProto\SecretChats;
2020-07-28 20:39:32 +02:00
use danog\MadelineProto\Loop\Update\UpdateLoop;
2019-10-31 20:48:06 +01:00
use danog\MadelineProto\MTProto;
/**
* Manages secret chats.
*
* https://core.telegram.org/api/end-to-end
*/
trait AuthKeyHandler
{
2019-10-31 20:48:06 +01:00
/**
* Temporary requested secret chats.
*
* @var array
*/
protected $temp_requested_secret_chats = [];
2019-10-31 20:48:06 +01:00
/**
* Secret chats.
*
* @var array
*/
protected $secret_chats = [];
2019-10-31 20:48:06 +01:00
/**
* Accept secret chat.
*
* @param array $params Secret chat ID
*
* @return \Generator
*/
public function acceptSecretChat($params): \Generator
2017-06-06 17:47:42 +02:00
{
2019-10-29 21:33:23 +01:00
//$this->logger->logger($params['id'],$this->secretChatStatus($params['id']));
if ($this->secretChatStatus($params['id']) !== 0) {
//$this->logger->logger($this->secretChatStatus($params['id']));
2020-04-05 22:22:47 +02:00
$this->logger->logger("I've already accepted secret chat ".$params['id']);
2017-06-02 13:25:05 +02:00
return false;
}
2020-01-31 19:49:58 +01:00
$dh_config = (yield from $this->getDhConfig());
2018-04-08 19:53:30 +02:00
$this->logger->logger('Generating b...', \danog\MadelineProto\Logger::VERBOSE);
$b = new \tgseclib\Math\BigInteger(\danog\MadelineProto\Tools::random(256), 256);
$params['g_a'] = new \tgseclib\Math\BigInteger((string) $params['g_a'], 256);
2019-10-29 21:33:23 +01:00
$this->checkG($params['g_a'], $dh_config['p']);
2019-09-02 17:08:36 +02:00
$key = ['auth_key' => \str_pad($params['g_a']->powMod($b, $dh_config['p'])->toBytes(), 256, \chr(0), \STR_PAD_LEFT)];
2018-04-08 19:53:30 +02:00
//$this->logger->logger($key);
2019-09-02 17:08:36 +02:00
$key['fingerprint'] = \substr(\sha1($key['auth_key'], true), -8);
$key['visualization_orig'] = \substr(\sha1($key['auth_key'], true), 16);
$key['visualization_46'] = \substr(\hash('sha256', $key['auth_key'], true), 20);
$this->secret_chats[$params['id']] = ['key' => $key, 'admin' => false, 'user_id' => $params['admin_id'], 'InputEncryptedChat' => ['_' => 'inputEncryptedChat', 'chat_id' => $params['id'], 'access_hash' => $params['access_hash']], 'in_seq_no_x' => 1, 'out_seq_no_x' => 0, 'in_seq_no' => 0, 'out_seq_no' => 0, 'layer' => 8, 'ttl' => 0, 'ttr' => 100, 'updated' => \time(), 'incoming' => [], 'outgoing' => [], 'created' => \time(), 'rekeying' => [0], 'key_x' => 'from server', 'mtproto' => 1];
$g_b = $dh_config['g']->powMod($b, $dh_config['p']);
2019-10-29 21:33:23 +01:00
$this->checkG($g_b, $dh_config['p']);
2020-02-05 17:37:01 +01:00
yield from $this->methodCallAsyncRead('messages.acceptEncryption', ['peer' => $params['id'], 'g_b' => $g_b->toBytes(), 'key_fingerprint' => $key['fingerprint']], ['datacenter' => $this->datacenter->curdc]);
2020-01-31 19:29:43 +01:00
yield from $this->notifyLayer($params['id']);
2020-04-05 22:22:47 +02:00
$this->logger->logger('Secret chat '.$params['id'].' accepted successfully!', \danog\MadelineProto\Logger::NOTICE);
}
2019-10-31 20:48:06 +01:00
/**
* Request secret chat.
*
* @param mixed $user User to start secret chat with
*
* @return \Generator
*/
public function requestSecretChat($user): \Generator
{
2020-01-31 19:49:58 +01:00
$user = (yield from $this->getInfo($user));
2017-05-02 12:13:27 +02:00
if (!isset($user['InputUser'])) {
throw new \danog\MadelineProto\Exception('This peer is not present in the internal peer database');
}
2017-05-02 12:13:01 +02:00
$user = $user['InputUser'];
2020-04-05 22:22:47 +02:00
$this->logger->logger('Creating secret chat with '.$user['user_id'].'...', \danog\MadelineProto\Logger::VERBOSE);
2020-01-31 19:49:58 +01:00
$dh_config = (yield from $this->getDhConfig());
2018-04-08 19:53:30 +02:00
$this->logger->logger('Generating a...', \danog\MadelineProto\Logger::VERBOSE);
$a = new \tgseclib\Math\BigInteger(\danog\MadelineProto\Tools::random(256), 256);
2018-04-08 19:53:30 +02:00
$this->logger->logger('Generating g_a...', \danog\MadelineProto\Logger::VERBOSE);
$g_a = $dh_config['g']->powMod($a, $dh_config['p']);
2019-10-29 21:33:23 +01:00
$this->checkG($g_a, $dh_config['p']);
2020-02-05 17:37:01 +01:00
$res = yield from $this->methodCallAsyncRead('messages.requestEncryption', ['user_id' => $user, 'g_a' => $g_a->toBytes()], ['datacenter' => $this->datacenter->curdc]);
$this->temp_requested_secret_chats[$res['id']] = $a;
2020-07-28 20:39:32 +02:00
$this->updaters[UpdateLoop::GENERIC]->resume();
2020-04-05 22:22:47 +02:00
$this->logger->logger('Secret chat '.$res['id'].' requested successfully!', \danog\MadelineProto\Logger::NOTICE);
return $res['id'];
}
2019-10-31 20:48:06 +01:00
/**
* Complete secret chat.
*
* @param array $params Secret chat
*
* @return \Generator
*/
2019-12-28 17:11:08 +01:00
private function completeSecretChat(array $params): \Generator
{
2019-10-29 21:33:23 +01:00
if ($this->secretChatStatus($params['id']) !== 1) {
//$this->logger->logger($this->secretChatStatus($params['id']));
2020-04-05 22:22:47 +02:00
$this->logger->logger('Could not find and complete secret chat '.$params['id']);
return false;
}
2020-01-31 19:49:58 +01:00
$dh_config = (yield from $this->getDhConfig());
$params['g_a_or_b'] = new \tgseclib\Math\BigInteger((string) $params['g_a_or_b'], 256);
2019-10-29 21:33:23 +01:00
$this->checkG($params['g_a_or_b'], $dh_config['p']);
2019-09-02 17:08:36 +02:00
$key = ['auth_key' => \str_pad($params['g_a_or_b']->powMod($this->temp_requested_secret_chats[$params['id']], $dh_config['p'])->toBytes(), 256, \chr(0), \STR_PAD_LEFT)];
unset($this->temp_requested_secret_chats[$params['id']]);
2019-09-02 17:08:36 +02:00
$key['fingerprint'] = \substr(\sha1($key['auth_key'], true), -8);
2018-04-08 19:53:30 +02:00
//$this->logger->logger($key);
if ($key['fingerprint'] !== $params['key_fingerprint']) {
2020-01-31 19:29:43 +01:00
yield from $this->discardSecretChat($params['id']);
throw new \danog\MadelineProto\SecurityException('Invalid key fingerprint!');
}
2019-09-02 17:08:36 +02:00
$key['visualization_orig'] = \substr(\sha1($key['auth_key'], true), 16);
$key['visualization_46'] = \substr(\hash('sha256', $key['auth_key'], true), 20);
$this->secret_chats[$params['id']] = ['key' => $key, 'admin' => true, 'user_id' => $params['participant_id'], 'InputEncryptedChat' => ['chat_id' => $params['id'], 'access_hash' => $params['access_hash'], '_' => 'inputEncryptedChat'], 'in_seq_no_x' => 0, 'out_seq_no_x' => 1, 'in_seq_no' => 0, 'out_seq_no' => 0, 'layer' => 8, 'ttl' => 0, 'ttr' => 100, 'updated' => \time(), 'incoming' => [], 'outgoing' => [], 'created' => \time(), 'rekeying' => [0], 'key_x' => 'to server', 'mtproto' => 1];
2020-01-31 19:29:43 +01:00
yield from $this->notifyLayer($params['id']);
2020-04-05 22:22:47 +02:00
$this->logger->logger('Secret chat '.$params['id'].' completed successfully!', \danog\MadelineProto\Logger::NOTICE);
}
2019-10-31 20:48:06 +01:00
private function notifyLayer($chat): \Generator
2019-05-02 21:30:50 +02:00
{
2020-02-05 17:37:01 +01:00
yield from $this->methodCallAsyncRead('messages.sendEncryptedService', ['peer' => $chat, 'message' => ['_' => 'decryptedMessageService', 'action' => ['_' => 'decryptedMessageActionNotifyLayer', 'layer' => $this->TL->getSecretLayer()]]], ['datacenter' => $this->datacenter->curdc]);
}
2019-10-31 20:48:06 +01:00
/**
* Temporary rekeyed secret chats.
*
* @var array
*/
protected $temp_rekeyed_secret_chats = [];
2019-10-31 20:48:06 +01:00
/**
* Rekey secret chat.
*
2019-12-28 17:11:08 +01:00
* @param int $chat Secret chat to rekey
2019-10-31 20:48:06 +01:00
*
* @return \Generator
*/
2019-12-28 17:11:08 +01:00
public function rekey(int $chat): \Generator
{
if ($this->secret_chats[$chat]['rekeying'][0] !== 0) {
return;
}
2020-04-05 22:22:47 +02:00
$this->logger->logger('Rekeying secret chat '.$chat.'...', \danog\MadelineProto\Logger::VERBOSE);
2020-01-31 19:49:58 +01:00
$dh_config = (yield from $this->getDhConfig());
2018-04-08 19:53:30 +02:00
$this->logger->logger('Generating a...', \danog\MadelineProto\Logger::VERBOSE);
$a = new \tgseclib\Math\BigInteger(\danog\MadelineProto\Tools::random(256), 256);
2018-04-08 19:53:30 +02:00
$this->logger->logger('Generating g_a...', \danog\MadelineProto\Logger::VERBOSE);
$g_a = $dh_config['g']->powMod($a, $dh_config['p']);
2019-10-29 21:33:23 +01:00
$this->checkG($g_a, $dh_config['p']);
2019-10-29 23:02:47 +01:00
$e = \danog\MadelineProto\Tools::random(8);
$this->temp_rekeyed_secret_chats[$e] = $a;
$this->secret_chats[$chat]['rekeying'] = [1, $e];
2020-02-05 17:37:01 +01:00
yield from $this->methodCallAsyncRead('messages.sendEncryptedService', ['peer' => $chat, 'message' => ['_' => 'decryptedMessageService', 'action' => ['_' => 'decryptedMessageActionRequestKey', 'g_a' => $g_a->toBytes(), 'exchange_id' => $e]]], ['datacenter' => $this->datacenter->curdc]);
2020-07-28 20:39:32 +02:00
$this->updaters[UpdateLoop::GENERIC]->resume();
return $e;
}
2019-10-31 20:48:06 +01:00
/**
* Accept rekeying.
*
2019-12-28 17:11:08 +01:00
* @param int $chat Chat
2019-10-31 20:48:06 +01:00
* @param array $params Parameters
*
* @return \Generator
*/
2019-12-28 17:11:08 +01:00
private function acceptRekey(int $chat, array $params): \Generator
{
if ($this->secret_chats[$chat]['rekeying'][0] !== 0) {
$my_exchange_id = new \tgseclib\Math\BigInteger($this->secret_chats[$chat]['rekeying'][1], -256);
$other_exchange_id = new \tgseclib\Math\BigInteger($params['exchange_id'], -256);
2018-04-08 19:53:30 +02:00
//$this->logger->logger($my, $params);
2019-07-18 23:59:02 +02:00
if ($my_exchange_id->compare($other_exchange_id) > 0) {
return;
}
2019-07-18 23:59:02 +02:00
if ($my_exchange_id->compare($other_exchange_id) === 0) {
$this->secret_chats[$chat]['rekeying'] = [0];
return;
}
}
2020-04-05 22:22:47 +02:00
$this->logger->logger('Accepting rekeying of secret chat '.$chat.'...', \danog\MadelineProto\Logger::VERBOSE);
2020-01-31 19:49:58 +01:00
$dh_config = (yield from $this->getDhConfig());
2018-04-08 19:53:30 +02:00
$this->logger->logger('Generating b...', \danog\MadelineProto\Logger::VERBOSE);
$b = new \tgseclib\Math\BigInteger(\danog\MadelineProto\Tools::random(256), 256);
$params['g_a'] = new \tgseclib\Math\BigInteger((string) $params['g_a'], 256);
2019-10-29 21:33:23 +01:00
$this->checkG($params['g_a'], $dh_config['p']);
2019-09-02 17:08:36 +02:00
$key = ['auth_key' => \str_pad($params['g_a']->powMod($b, $dh_config['p'])->toBytes(), 256, \chr(0), \STR_PAD_LEFT)];
$key['fingerprint'] = \substr(\sha1($key['auth_key'], true), -8);
$key['visualization_orig'] = $this->secret_chats[$chat]['key']['visualization_orig'];
2019-09-02 17:08:36 +02:00
$key['visualization_46'] = \substr(\hash('sha256', $key['auth_key'], true), 20);
$this->temp_rekeyed_secret_chats[$params['exchange_id']] = $key;
$this->secret_chats[$chat]['rekeying'] = [2, $params['exchange_id']];
$g_b = $dh_config['g']->powMod($b, $dh_config['p']);
2019-10-29 21:33:23 +01:00
$this->checkG($g_b, $dh_config['p']);
2020-02-05 17:37:01 +01:00
yield from $this->methodCallAsyncRead('messages.sendEncryptedService', ['peer' => $chat, 'message' => ['_' => 'decryptedMessageService', 'action' => ['_' => 'decryptedMessageActionAcceptKey', 'g_b' => $g_b->toBytes(), 'exchange_id' => $params['exchange_id'], 'key_fingerprint' => $key['fingerprint']]]], ['datacenter' => $this->datacenter->curdc]);
2020-07-28 20:39:32 +02:00
$this->updaters[UpdateLoop::GENERIC]->resume();
}
2019-10-31 20:48:06 +01:00
/**
* Commit rekeying of secret chat.
*
2019-12-28 17:11:08 +01:00
* @param int $chat Chat
2019-10-31 20:48:06 +01:00
* @param array $params Parameters
*
* @return \Generator
*/
2019-12-28 17:11:08 +01:00
private function commitRekey(int $chat, array $params): \Generator
{
2017-12-16 19:08:11 +01:00
if ($this->secret_chats[$chat]['rekeying'][0] !== 1 || !isset($this->temp_rekeyed_secret_chats[$params['exchange_id']])) {
$this->secret_chats[$chat]['rekeying'] = [0];
return;
}
2020-04-05 22:22:47 +02:00
$this->logger->logger('Committing rekeying of secret chat '.$chat.'...', \danog\MadelineProto\Logger::VERBOSE);
2020-01-31 19:49:58 +01:00
$dh_config = (yield from $this->getDhConfig());
$params['g_b'] = new \tgseclib\Math\BigInteger((string) $params['g_b'], 256);
2019-10-29 21:33:23 +01:00
$this->checkG($params['g_b'], $dh_config['p']);
2019-09-02 17:08:36 +02:00
$key = ['auth_key' => \str_pad($params['g_b']->powMod($this->temp_rekeyed_secret_chats[$params['exchange_id']], $dh_config['p'])->toBytes(), 256, \chr(0), \STR_PAD_LEFT)];
$key['fingerprint'] = \substr(\sha1($key['auth_key'], true), -8);
$key['visualization_orig'] = $this->secret_chats[$chat]['key']['visualization_orig'];
2019-09-02 17:08:36 +02:00
$key['visualization_46'] = \substr(\hash('sha256', $key['auth_key'], true), 20);
if ($key['fingerprint'] !== $params['key_fingerprint']) {
2020-02-05 17:37:01 +01:00
yield from $this->methodCallAsyncRead('messages.sendEncryptedService', ['peer' => $chat, 'message' => ['_' => 'decryptedMessageService', 'action' => ['_' => 'decryptedMessageActionAbortKey', 'exchange_id' => $params['exchange_id']]]], ['datacenter' => $this->datacenter->curdc]);
throw new \danog\MadelineProto\SecurityException('Invalid key fingerprint!');
}
2020-02-05 17:37:01 +01:00
yield from $this->methodCallAsyncRead('messages.sendEncryptedService', ['peer' => $chat, 'message' => ['_' => 'decryptedMessageService', 'action' => ['_' => 'decryptedMessageActionCommitKey', 'exchange_id' => $params['exchange_id'], 'key_fingerprint' => $key['fingerprint']]]], ['datacenter' => $this->datacenter->curdc]);
unset($this->temp_rekeyed_secret_chats[$params['exchange_id']]);
$this->secret_chats[$chat]['rekeying'] = [0];
$this->secret_chats[$chat]['old_key'] = $this->secret_chats[$chat]['key'];
$this->secret_chats[$chat]['key'] = $key;
$this->secret_chats[$chat]['ttr'] = 100;
2019-09-02 17:08:36 +02:00
$this->secret_chats[$chat]['updated'] = \time();
2020-07-28 20:39:32 +02:00
$this->updaters[UpdateLoop::GENERIC]->resume();
}
2019-10-31 20:48:06 +01:00
/**
* Complete rekeying.
*
2019-12-28 17:11:08 +01:00
* @param int $chat Chat
2019-10-31 20:48:06 +01:00
* @param array $params Parameters
*
* @return \Generator
*/
2019-12-28 17:11:08 +01:00
private function completeRekey(int $chat, array $params): \Generator
{
if ($this->secret_chats[$chat]['rekeying'][0] !== 2 || !isset($this->temp_rekeyed_secret_chats[$params['exchange_id']]['fingerprint'])) {
return;
}
if ($this->temp_rekeyed_secret_chats[$params['exchange_id']]['fingerprint'] !== $params['key_fingerprint']) {
2020-02-05 17:37:01 +01:00
yield from $this->methodCallAsyncRead('messages.sendEncryptedService', ['peer' => $chat, 'message' => ['_' => 'decryptedMessageService', 'action' => ['_' => 'decryptedMessageActionAbortKey', 'exchange_id' => $params['exchange_id']]]], ['datacenter' => $this->datacenter->curdc]);
throw new \danog\MadelineProto\SecurityException('Invalid key fingerprint!');
}
2020-04-05 22:22:47 +02:00
$this->logger->logger('Completing rekeying of secret chat '.$chat.'...', \danog\MadelineProto\Logger::VERBOSE);
$this->secret_chats[$chat]['rekeying'] = [0];
$this->secret_chats[$chat]['old_key'] = $this->secret_chats[$chat]['key'];
$this->secret_chats[$chat]['key'] = $this->temp_rekeyed_secret_chats[$params['exchange_id']];
$this->secret_chats[$chat]['ttr'] = 100;
2019-09-02 17:08:36 +02:00
$this->secret_chats[$chat]['updated'] = \time();
unset($this->temp_rekeyed_secret_chats[$params['exchange_id']]);
2020-02-05 17:37:01 +01:00
yield from $this->methodCallAsyncRead('messages.sendEncryptedService', ['peer' => $chat, 'message' => ['_' => 'decryptedMessageService', 'action' => ['_' => 'decryptedMessageActionNoop']]], ['datacenter' => $this->datacenter->curdc]);
2020-04-05 22:22:47 +02:00
$this->logger->logger('Secret chat '.$chat.' rekeyed successfully!', \danog\MadelineProto\Logger::VERBOSE);
2017-06-01 18:53:05 +02:00
return true;
}
2019-10-31 20:48:06 +01:00
/**
* Get secret chat status.
*
* @param int $chat Chat ID
*
* @return int One of MTProto::SECRET_EMPTY, MTProto::SECRET_REQUESTED, MTProto::SECRET_READY
*/
public function secretChatStatus(int $chat): int
{
if (isset($this->secret_chats[$chat])) {
2019-10-31 20:48:06 +01:00
return MTProto::SECRET_READY;
}
if (isset($this->temp_requested_secret_chats[$chat])) {
2019-10-31 20:48:06 +01:00
return MTProto::SECRET_REQUESTED;
}
2019-10-31 20:48:06 +01:00
return MTProto::SECRET_EMPTY;
}
2019-10-31 20:48:06 +01:00
/**
* Get secret chat.
*
* @param array|int $chat Secret chat ID
*
* @return array
*/
public function getSecretChat($chat): array
2017-04-02 16:43:47 +02:00
{
2019-09-02 17:08:36 +02:00
return $this->secret_chats[\is_array($chat) ? $chat['chat_id'] : $chat];
2017-04-02 16:43:47 +02:00
}
2019-10-31 20:48:06 +01:00
/**
* Check whether secret chat exists.
*
* @param array|int $chat Secret chat ID
*
* @return boolean
*/
public function hasSecretChat($chat): bool
{
return isset($this->secret_chats[\is_array($chat) ? $chat['chat_id'] : $chat]);
}
/**
* Discard secret chat.
*
2019-12-28 17:11:08 +01:00
* @param int $chat Secret chat ID
2019-10-31 20:48:06 +01:00
*
* @return \Generator
*/
2019-12-28 17:11:08 +01:00
public function discardSecretChat(int $chat): \Generator
2017-06-06 17:47:42 +02:00
{
2020-04-05 22:22:47 +02:00
$this->logger->logger('Discarding secret chat '.$chat.'...', \danog\MadelineProto\Logger::VERBOSE);
2017-06-02 13:25:05 +02:00
if (isset($this->secret_chats[$chat])) {
unset($this->secret_chats[$chat]);
}
if (isset($this->temp_requested_secret_chats[$chat])) {
unset($this->temp_requested_secret_chats[$chat]);
}
try {
2020-02-05 17:37:01 +01:00
yield from $this->methodCallAsyncRead('messages.discardEncryption', ['chat_id' => $chat], ['datacenter' => $this->datacenter->curdc]);
2017-06-02 13:25:05 +02:00
} catch (\danog\MadelineProto\RPCErrorException $e) {
2017-06-06 17:47:42 +02:00
if ($e->rpc !== 'ENCRYPTION_ALREADY_DECLINED') {
throw $e;
}
2017-06-02 13:25:05 +02:00
}
}
2018-02-24 17:54:39 +01:00
}