Common.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. <?php
  2. declare(strict_types=1);
  3. namespace PhpMyAdmin;
  4. use PhpMyAdmin\ConfigStorage\Relation;
  5. use PhpMyAdmin\Dbal\DatabaseName;
  6. use PhpMyAdmin\Dbal\TableName;
  7. use PhpMyAdmin\Http\Factory\ServerRequestFactory;
  8. use PhpMyAdmin\Http\ServerRequest;
  9. use PhpMyAdmin\Plugins\AuthenticationPlugin;
  10. use PhpMyAdmin\SqlParser\Lexer;
  11. use Symfony\Component\DependencyInjection\ContainerInterface;
  12. use Webmozart\Assert\Assert;
  13. use Webmozart\Assert\InvalidArgumentException;
  14. use function __;
  15. use function array_pop;
  16. use function count;
  17. use function date_default_timezone_get;
  18. use function date_default_timezone_set;
  19. use function define;
  20. use function defined;
  21. use function explode;
  22. use function extension_loaded;
  23. use function function_exists;
  24. use function hash_equals;
  25. use function htmlspecialchars;
  26. use function implode;
  27. use function ini_get;
  28. use function ini_set;
  29. use function is_array;
  30. use function is_scalar;
  31. use function mb_internal_encoding;
  32. use function mb_strlen;
  33. use function mb_strpos;
  34. use function mb_strrpos;
  35. use function mb_substr;
  36. use function register_shutdown_function;
  37. use function session_id;
  38. use function str_replace;
  39. use function strlen;
  40. use function trigger_error;
  41. use function urldecode;
  42. use const E_USER_ERROR;
  43. final class Common
  44. {
  45. /**
  46. * Misc stuff and REQUIRED by ALL the scripts.
  47. * MUST be included by every script
  48. *
  49. * Among other things, it contains the advanced authentication work.
  50. *
  51. * Order of sections:
  52. *
  53. * the authentication libraries must be before the connection to db
  54. *
  55. * ... so the required order is:
  56. *
  57. * LABEL_variables_init
  58. * - initialize some variables always needed
  59. * LABEL_parsing_config_file
  60. * - parsing of the configuration file
  61. * LABEL_loading_language_file
  62. * - loading language file
  63. * LABEL_setup_servers
  64. * - check and setup configured servers
  65. * LABEL_theme_setup
  66. * - setting up themes
  67. *
  68. * - load of MySQL extension (if necessary)
  69. * - loading of an authentication library
  70. * - db connection
  71. * - authentication work
  72. */
  73. public static function run(): void
  74. {
  75. global $containerBuilder, $errorHandler, $config, $server, $dbi, $request;
  76. global $lang, $cfg, $isConfigLoading, $auth_plugin, $route, $theme;
  77. global $urlParams, $isMinimumCommon, $sql_query, $token_mismatch;
  78. $request = ServerRequestFactory::createFromGlobals();
  79. $route = Routing::getCurrentRoute();
  80. if ($route === '/import-status') {
  81. $isMinimumCommon = true;
  82. }
  83. $containerBuilder = Core::getContainerBuilder();
  84. /** @var ErrorHandler $errorHandler */
  85. $errorHandler = $containerBuilder->get('error_handler');
  86. self::checkRequiredPhpExtensions();
  87. self::configurePhpSettings();
  88. self::cleanupPathInfo();
  89. /* parsing configuration file LABEL_parsing_config_file */
  90. /** @var bool $isConfigLoading Indication for the error handler */
  91. $isConfigLoading = false;
  92. register_shutdown_function([Config::class, 'fatalErrorHandler']);
  93. /**
  94. * Force reading of config file, because we removed sensitive values
  95. * in the previous iteration.
  96. *
  97. * @var Config $config
  98. */
  99. $config = $containerBuilder->get('config');
  100. /**
  101. * include session handling after the globals, to prevent overwriting
  102. */
  103. if (! defined('PMA_NO_SESSION')) {
  104. Session::setUp($config, $errorHandler);
  105. }
  106. $request = Core::populateRequestWithEncryptedQueryParams($request);
  107. /**
  108. * init some variables LABEL_variables_init
  109. */
  110. /**
  111. * holds parameters to be passed to next page
  112. *
  113. * @global array $urlParams
  114. */
  115. $urlParams = [];
  116. $containerBuilder->setParameter('url_params', $urlParams);
  117. self::setGotoAndBackGlobals($containerBuilder, $config);
  118. self::checkTokenRequestParam();
  119. self::setDatabaseAndTableFromRequest($containerBuilder, $request);
  120. /**
  121. * SQL query to be executed
  122. *
  123. * @global string $sql_query
  124. */
  125. $sql_query = '';
  126. if ($request->isPost()) {
  127. $sql_query = $request->getParsedBodyParam('sql_query', '');
  128. }
  129. $containerBuilder->setParameter('sql_query', $sql_query);
  130. //$_REQUEST['set_theme'] // checked later in this file LABEL_theme_setup
  131. //$_REQUEST['server']; // checked later in this file
  132. //$_REQUEST['lang']; // checked by LABEL_loading_language_file
  133. /* loading language file LABEL_loading_language_file */
  134. /**
  135. * lang detection is done here
  136. */
  137. $language = LanguageManager::getInstance()->selectLanguage();
  138. $language->activate();
  139. /**
  140. * check for errors occurred while loading configuration
  141. * this check is done here after loading language files to present errors in locale
  142. */
  143. $config->checkPermissions();
  144. $config->checkErrors();
  145. self::checkServerConfiguration();
  146. self::checkRequest();
  147. /* setup servers LABEL_setup_servers */
  148. $config->checkServers();
  149. /**
  150. * current server
  151. *
  152. * @global integer $server
  153. */
  154. $server = $config->selectServer();
  155. $urlParams['server'] = $server;
  156. $containerBuilder->setParameter('server', $server);
  157. $containerBuilder->setParameter('url_params', $urlParams);
  158. $cfg = $config->settings;
  159. /* setup themes LABEL_theme_setup */
  160. $theme = ThemeManager::initializeTheme();
  161. /** @var DatabaseInterface $dbi */
  162. $dbi = null;
  163. if (isset($isMinimumCommon)) {
  164. $config->loadUserPreferences();
  165. $containerBuilder->set('theme_manager', ThemeManager::getInstance());
  166. Tracker::enable();
  167. return;
  168. }
  169. /**
  170. * save some settings in cookies
  171. *
  172. * @todo should be done in PhpMyAdmin\Config
  173. */
  174. $config->setCookie('pma_lang', (string) $lang);
  175. ThemeManager::getInstance()->setThemeCookie();
  176. $dbi = DatabaseInterface::load();
  177. $containerBuilder->set(DatabaseInterface::class, $dbi);
  178. $containerBuilder->setAlias('dbi', DatabaseInterface::class);
  179. if (! empty($cfg['Server'])) {
  180. $config->getLoginCookieValidityFromCache($server);
  181. $auth_plugin = Plugins::getAuthPlugin();
  182. $auth_plugin->authenticate();
  183. /* Enable LOAD DATA LOCAL INFILE for LDI plugin */
  184. if ($route === '/import' && ($_POST['format'] ?? '') === 'ldi') {
  185. // Switch this before the DB connection is done
  186. // phpcs:disable PSR1.Files.SideEffects
  187. define('PMA_ENABLE_LDI', 1);
  188. // phpcs:enable
  189. }
  190. self::connectToDatabaseServer($dbi, $auth_plugin);
  191. $auth_plugin->rememberCredentials();
  192. $auth_plugin->checkTwoFactor();
  193. /* Log success */
  194. Logging::logUser($cfg['Server']['user']);
  195. if ($dbi->getVersion() < $cfg['MysqlMinVersion']['internal']) {
  196. Core::fatalError(
  197. __('You should upgrade to %s %s or later.'),
  198. [
  199. 'MySQL',
  200. $cfg['MysqlMinVersion']['human'],
  201. ]
  202. );
  203. }
  204. // Sets the default delimiter (if specified).
  205. $sqlDelimiter = $request->getParam('sql_delimiter', '');
  206. if (strlen($sqlDelimiter) > 0) {
  207. // phpcs:ignore Squiz.NamingConventions.ValidVariableName.MemberNotCamelCaps
  208. Lexer::$DEFAULT_DELIMITER = $sqlDelimiter;
  209. }
  210. // TODO: Set SQL modes too.
  211. } else { // end server connecting
  212. $response = ResponseRenderer::getInstance();
  213. $response->getHeader()->disableMenuAndConsole();
  214. $response->getFooter()->setMinimal();
  215. }
  216. $response = ResponseRenderer::getInstance();
  217. /**
  218. * There is no point in even attempting to process
  219. * an ajax request if there is a token mismatch
  220. */
  221. if ($response->isAjax() && $request->isPost() && $token_mismatch) {
  222. $response->setRequestStatus(false);
  223. $response->addJSON(
  224. 'message',
  225. Message::error(__('Error: Token mismatch'))
  226. );
  227. exit;
  228. }
  229. Profiling::check($dbi, $response);
  230. $containerBuilder->set('response', ResponseRenderer::getInstance());
  231. // load user preferences
  232. $config->loadUserPreferences();
  233. $containerBuilder->set('theme_manager', ThemeManager::getInstance());
  234. /* Tell tracker that it can actually work */
  235. Tracker::enable();
  236. if (empty($server) || ! isset($cfg['ZeroConf']) || $cfg['ZeroConf'] !== true) {
  237. return;
  238. }
  239. /** @var Relation $relation */
  240. $relation = $containerBuilder->get('relation');
  241. $dbi->postConnectControl($relation);
  242. }
  243. /**
  244. * Checks that required PHP extensions are there.
  245. */
  246. private static function checkRequiredPhpExtensions(): void
  247. {
  248. /**
  249. * Warning about mbstring.
  250. */
  251. if (! function_exists('mb_detect_encoding')) {
  252. Core::warnMissingExtension('mbstring');
  253. }
  254. /**
  255. * Warning about mysqlnd. This does not apply to PMA >= 6.0
  256. */
  257. if (! function_exists('mysqli_stmt_get_result')) {
  258. Core::warnMissingExtension('mysqlnd');
  259. }
  260. /**
  261. * We really need this one!
  262. */
  263. if (! function_exists('preg_replace')) {
  264. Core::warnMissingExtension('pcre', true);
  265. }
  266. /**
  267. * JSON is required in several places.
  268. */
  269. if (! function_exists('json_encode')) {
  270. Core::warnMissingExtension('json', true);
  271. }
  272. /**
  273. * ctype is required for Twig.
  274. */
  275. if (! function_exists('ctype_alpha')) {
  276. Core::warnMissingExtension('ctype', true);
  277. }
  278. /**
  279. * hash is required for cookie authentication.
  280. */
  281. if (function_exists('hash_hmac')) {
  282. return;
  283. }
  284. Core::warnMissingExtension('hash', true);
  285. }
  286. /**
  287. * Applies changes to PHP configuration.
  288. */
  289. private static function configurePhpSettings(): void
  290. {
  291. /**
  292. * Set utf-8 encoding for PHP
  293. */
  294. ini_set('default_charset', 'utf-8');
  295. mb_internal_encoding('utf-8');
  296. /**
  297. * Set precision to sane value, with higher values
  298. * things behave slightly unexpectedly, for example
  299. * round(1.2, 2) returns 1.199999999999999956.
  300. */
  301. ini_set('precision', '14');
  302. /**
  303. * check timezone setting
  304. * this could produce an E_WARNING - but only once,
  305. * if not done here it will produce E_WARNING on every date/time function
  306. */
  307. date_default_timezone_set(@date_default_timezone_get());
  308. }
  309. /**
  310. * PATH_INFO could be compromised if set, so remove it from PHP_SELF
  311. * and provide a clean PHP_SELF here
  312. */
  313. public static function cleanupPathInfo(): void
  314. {
  315. global $PMA_PHP_SELF;
  316. $PMA_PHP_SELF = Core::getenv('PHP_SELF');
  317. if (empty($PMA_PHP_SELF)) {
  318. $PMA_PHP_SELF = urldecode(Core::getenv('REQUEST_URI'));
  319. }
  320. $_PATH_INFO = Core::getenv('PATH_INFO');
  321. if (! empty($_PATH_INFO) && ! empty($PMA_PHP_SELF)) {
  322. $question_pos = mb_strpos($PMA_PHP_SELF, '?');
  323. if ($question_pos != false) {
  324. $PMA_PHP_SELF = mb_substr($PMA_PHP_SELF, 0, $question_pos);
  325. }
  326. $path_info_pos = mb_strrpos($PMA_PHP_SELF, $_PATH_INFO);
  327. if ($path_info_pos !== false) {
  328. $path_info_part = mb_substr($PMA_PHP_SELF, $path_info_pos, mb_strlen($_PATH_INFO));
  329. if ($path_info_part == $_PATH_INFO) {
  330. $PMA_PHP_SELF = mb_substr($PMA_PHP_SELF, 0, $path_info_pos);
  331. }
  332. }
  333. }
  334. $path = [];
  335. foreach (explode('/', $PMA_PHP_SELF) as $part) {
  336. // ignore parts that have no value
  337. if (empty($part) || $part === '.') {
  338. continue;
  339. }
  340. if ($part !== '..') {
  341. // cool, we found a new part
  342. $path[] = $part;
  343. } elseif (count($path) > 0) {
  344. // going back up? sure
  345. array_pop($path);
  346. }
  347. // Here we intentionall ignore case where we go too up
  348. // as there is nothing sane to do
  349. }
  350. $PMA_PHP_SELF = htmlspecialchars('/' . implode('/', $path));
  351. }
  352. private static function setGotoAndBackGlobals(ContainerInterface $container, Config $config): void
  353. {
  354. global $goto, $back, $urlParams;
  355. // Holds page that should be displayed.
  356. $goto = '';
  357. $container->setParameter('goto', $goto);
  358. if (isset($_REQUEST['goto']) && Core::checkPageValidity($_REQUEST['goto'])) {
  359. $goto = $_REQUEST['goto'];
  360. $urlParams['goto'] = $goto;
  361. $container->setParameter('goto', $goto);
  362. $container->setParameter('url_params', $urlParams);
  363. } else {
  364. if ($config->issetCookie('goto')) {
  365. $config->removeCookie('goto');
  366. }
  367. unset($_REQUEST['goto'], $_GET['goto'], $_POST['goto']);
  368. }
  369. if (isset($_REQUEST['back']) && Core::checkPageValidity($_REQUEST['back'])) {
  370. // Returning page.
  371. $back = $_REQUEST['back'];
  372. $container->setParameter('back', $back);
  373. return;
  374. }
  375. if ($config->issetCookie('back')) {
  376. $config->removeCookie('back');
  377. }
  378. unset($_REQUEST['back'], $_GET['back'], $_POST['back']);
  379. }
  380. /**
  381. * Check whether user supplied token is valid, if not remove any possibly
  382. * dangerous stuff from request.
  383. *
  384. * Check for token mismatch only if the Request method is POST.
  385. * GET Requests would never have token and therefore checking
  386. * mis-match does not make sense.
  387. */
  388. public static function checkTokenRequestParam(): void
  389. {
  390. global $token_mismatch, $token_provided;
  391. $token_mismatch = true;
  392. $token_provided = false;
  393. if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
  394. return;
  395. }
  396. if (isset($_POST['token']) && is_scalar($_POST['token']) && strlen((string) $_POST['token']) > 0) {
  397. $token_provided = true;
  398. $token_mismatch = ! @hash_equals($_SESSION[' PMA_token '], (string) $_POST['token']);
  399. }
  400. if (! $token_mismatch) {
  401. return;
  402. }
  403. // Warn in case the mismatch is result of failed setting of session cookie
  404. if (isset($_POST['set_session']) && $_POST['set_session'] !== session_id()) {
  405. trigger_error(
  406. __(
  407. 'Failed to set session cookie. Maybe you are using HTTP instead of HTTPS to access phpMyAdmin.'
  408. ),
  409. E_USER_ERROR
  410. );
  411. }
  412. /**
  413. * We don't allow any POST operation parameters if the token is mismatched
  414. * or is not provided.
  415. */
  416. $allowList = ['ajax_request'];
  417. Sanitize::removeRequestVars($allowList);
  418. }
  419. private static function setDatabaseAndTableFromRequest(
  420. ContainerInterface $containerBuilder,
  421. ServerRequest $request
  422. ): void {
  423. global $db, $table, $urlParams;
  424. try {
  425. $db = DatabaseName::fromValue($request->getParam('db'))->getName();
  426. } catch (InvalidArgumentException $exception) {
  427. $db = '';
  428. }
  429. try {
  430. Assert::stringNotEmpty($db);
  431. $table = TableName::fromValue($request->getParam('table'))->getName();
  432. } catch (InvalidArgumentException $exception) {
  433. $table = '';
  434. }
  435. if (! is_array($urlParams)) {
  436. $urlParams = [];
  437. }
  438. $urlParams['db'] = $db;
  439. $urlParams['table'] = $table;
  440. // If some parameter value includes the % character, you need to escape it by adding
  441. // another % so Symfony doesn't consider it a reference to a parameter name.
  442. $containerBuilder->setParameter('db', str_replace('%', '%%', $db));
  443. $containerBuilder->setParameter('table', str_replace('%', '%%', $table));
  444. $containerBuilder->setParameter('url_params', $urlParams);
  445. }
  446. /**
  447. * Check whether PHP configuration matches our needs.
  448. */
  449. private static function checkServerConfiguration(): void
  450. {
  451. /**
  452. * As we try to handle charsets by ourself, mbstring overloads just
  453. * break it, see bug 1063821.
  454. *
  455. * We specifically use empty here as we are looking for anything else than
  456. * empty value or 0.
  457. */
  458. if (extension_loaded('mbstring') && ! empty(ini_get('mbstring.func_overload'))) {
  459. Core::fatalError(
  460. __(
  461. 'You have enabled mbstring.func_overload in your PHP '
  462. . 'configuration. This option is incompatible with phpMyAdmin '
  463. . 'and might cause some data to be corrupted!'
  464. )
  465. );
  466. }
  467. /**
  468. * The ini_set and ini_get functions can be disabled using
  469. * disable_functions but we're relying quite a lot of them.
  470. */
  471. if (function_exists('ini_get') && function_exists('ini_set')) {
  472. return;
  473. }
  474. Core::fatalError(
  475. __(
  476. 'The ini_get and/or ini_set functions are disabled in php.ini. phpMyAdmin requires these functions!'
  477. )
  478. );
  479. }
  480. /**
  481. * Checks request and fails with fatal error if something problematic is found
  482. */
  483. private static function checkRequest(): void
  484. {
  485. if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS'])) {
  486. Core::fatalError(__('GLOBALS overwrite attempt'));
  487. }
  488. /**
  489. * protect against possible exploits - there is no need to have so much variables
  490. */
  491. if (count($_REQUEST) <= 1000) {
  492. return;
  493. }
  494. Core::fatalError(__('possible exploit'));
  495. }
  496. private static function connectToDatabaseServer(DatabaseInterface $dbi, AuthenticationPlugin $auth): void
  497. {
  498. global $cfg;
  499. /**
  500. * Try to connect MySQL with the control user profile (will be used to get the privileges list for the current
  501. * user but the true user link must be open after this one so it would be default one for all the scripts).
  502. */
  503. $controlLink = false;
  504. if ($cfg['Server']['controluser'] !== '') {
  505. $controlLink = $dbi->connect(DatabaseInterface::CONNECT_CONTROL);
  506. }
  507. // Connects to the server (validates user's login)
  508. $userLink = $dbi->connect(DatabaseInterface::CONNECT_USER);
  509. if ($userLink === false) {
  510. $auth->showFailure('mysql-denied');
  511. }
  512. if ($controlLink) {
  513. return;
  514. }
  515. /**
  516. * Open separate connection for control queries, this is needed to avoid problems with table locking used in
  517. * main connection and phpMyAdmin issuing queries to configuration storage, which is not locked by that time.
  518. */
  519. $dbi->connect(DatabaseInterface::CONNECT_USER, null, DatabaseInterface::CONNECT_CONTROL);
  520. }
  521. }