PageRenderTime 42ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/libraries/classes/Server/Privileges.php

http://github.com/phpmyadmin/phpmyadmin
PHP | 3898 lines | 3136 code | 318 blank | 444 comment | 365 complexity | 304f267100282d8151c48a3d443ea6fe MD5 | raw file
Possible License(s): GPL-2.0, MIT, LGPL-3.0
  1. <?php
  2. /**
  3. * set of functions with the Privileges section in pma
  4. */
  5. declare(strict_types=1);
  6. namespace PhpMyAdmin\Server;
  7. use mysqli_stmt;
  8. use PhpMyAdmin\DatabaseInterface;
  9. use PhpMyAdmin\Html\Generator;
  10. use PhpMyAdmin\Html\MySQLDocumentation;
  11. use PhpMyAdmin\Message;
  12. use PhpMyAdmin\Query\Compatibility;
  13. use PhpMyAdmin\Relation;
  14. use PhpMyAdmin\RelationCleanup;
  15. use PhpMyAdmin\ResponseRenderer;
  16. use PhpMyAdmin\Template;
  17. use PhpMyAdmin\Url;
  18. use PhpMyAdmin\Util;
  19. use function __;
  20. use function array_map;
  21. use function array_merge;
  22. use function array_unique;
  23. use function count;
  24. use function explode;
  25. use function htmlspecialchars;
  26. use function implode;
  27. use function in_array;
  28. use function is_array;
  29. use function is_scalar;
  30. use function is_string;
  31. use function json_decode;
  32. use function ksort;
  33. use function max;
  34. use function mb_chr;
  35. use function mb_strpos;
  36. use function mb_strrpos;
  37. use function mb_strtolower;
  38. use function mb_strtoupper;
  39. use function mb_substr;
  40. use function preg_match;
  41. use function preg_replace;
  42. use function sprintf;
  43. use function str_contains;
  44. use function str_replace;
  45. use function strlen;
  46. use function trim;
  47. use function uksort;
  48. /**
  49. * Privileges class
  50. */
  51. class Privileges
  52. {
  53. /** @var Template */
  54. public $template;
  55. /** @var RelationCleanup */
  56. private $relationCleanup;
  57. /** @var DatabaseInterface */
  58. public $dbi;
  59. /** @var Relation */
  60. public $relation;
  61. /** @var Plugins */
  62. private $plugins;
  63. /**
  64. * @param Template $template Template object
  65. * @param DatabaseInterface $dbi DatabaseInterface object
  66. * @param Relation $relation Relation object
  67. * @param RelationCleanup $relationCleanup RelationCleanup object
  68. */
  69. public function __construct(
  70. Template $template,
  71. $dbi,
  72. Relation $relation,
  73. RelationCleanup $relationCleanup,
  74. Plugins $plugins
  75. ) {
  76. $this->template = $template;
  77. $this->dbi = $dbi;
  78. $this->relation = $relation;
  79. $this->relationCleanup = $relationCleanup;
  80. $this->plugins = $plugins;
  81. }
  82. /**
  83. * Escapes wildcard in a database+table specification
  84. * before using it in a GRANT statement.
  85. *
  86. * Escaping a wildcard character in a GRANT is only accepted at the global
  87. * or database level, not at table level; this is why I remove
  88. * the escaping character. Internally, in mysql.tables_priv.Db there are
  89. * no escaping (for example test_db) but in mysql.db you'll see test\_db
  90. * for a db-specific privilege.
  91. *
  92. * @param string $dbname Database name
  93. * @param string $tablename Table name
  94. *
  95. * @return string the escaped (if necessary) database.table
  96. */
  97. public function wildcardEscapeForGrant(string $dbname, string $tablename): string
  98. {
  99. if (strlen($dbname) === 0) {
  100. return '*.*';
  101. }
  102. if (strlen($tablename) > 0) {
  103. return Util::backquote(
  104. Util::unescapeMysqlWildcards($dbname)
  105. )
  106. . '.' . Util::backquote($tablename);
  107. }
  108. return Util::backquote($dbname) . '.*';
  109. }
  110. /**
  111. * Generates a condition on the user name
  112. *
  113. * @param string|null $initial the user's initial
  114. *
  115. * @return string the generated condition
  116. */
  117. public function rangeOfUsers($initial = '')
  118. {
  119. // strtolower() is used because the User field
  120. // might be BINARY, so LIKE would be case sensitive
  121. if ($initial === null || $initial === '') {
  122. return '';
  123. }
  124. return " WHERE `User` LIKE '"
  125. . $this->dbi->escapeString($initial) . "%'"
  126. . " OR `User` LIKE '"
  127. . $this->dbi->escapeString(mb_strtolower($initial))
  128. . "%'";
  129. }
  130. /**
  131. * Parses privileges into an array, it modifies the array
  132. *
  133. * @param array $row Results row from
  134. */
  135. public function fillInTablePrivileges(array &$row): void
  136. {
  137. $row1 = $this->dbi->fetchSingleRow('SHOW COLUMNS FROM `mysql`.`tables_priv` LIKE \'Table_priv\';', 'ASSOC');
  138. // note: in MySQL 5.0.3 we get "Create View', 'Show view';
  139. // the View for Create is spelled with uppercase V
  140. // the view for Show is spelled with lowercase v
  141. // and there is a space between the words
  142. $avGrants = explode(
  143. '\',\'',
  144. mb_substr(
  145. $row1['Type'],
  146. mb_strpos($row1['Type'], '(') + 2,
  147. mb_strpos($row1['Type'], ')')
  148. - mb_strpos($row1['Type'], '(') - 3
  149. )
  150. );
  151. $usersGrants = explode(',', $row['Table_priv']);
  152. foreach ($avGrants as $currentGrant) {
  153. $row[$currentGrant . '_priv'] = in_array($currentGrant, $usersGrants) ? 'Y' : 'N';
  154. }
  155. unset($row['Table_priv']);
  156. }
  157. /**
  158. * Extracts the privilege information of a priv table row
  159. *
  160. * @param array|null $row the row
  161. * @param bool $enableHTML add <dfn> tag with tooltips
  162. * @param bool $tablePrivs whether row contains table privileges
  163. *
  164. * @return array
  165. *
  166. * @global resource $user_link the database connection
  167. */
  168. public function extractPrivInfo($row = null, $enableHTML = false, $tablePrivs = false)
  169. {
  170. if ($tablePrivs) {
  171. $grants = $this->getTableGrantsArray();
  172. } else {
  173. $grants = $this->getGrantsArray();
  174. }
  175. if ($row !== null && isset($row['Table_priv'])) {
  176. $this->fillInTablePrivileges($row);
  177. }
  178. $privs = [];
  179. $allPrivileges = true;
  180. foreach ($grants as $currentGrant) {
  181. if (
  182. ($row === null || ! isset($row[$currentGrant[0]]))
  183. && ($row !== null || ! isset($GLOBALS[$currentGrant[0]]))
  184. ) {
  185. continue;
  186. }
  187. if (
  188. ($row !== null && $row[$currentGrant[0]] === 'Y')
  189. || ($row === null
  190. && ($GLOBALS[$currentGrant[0]] === 'Y'
  191. || (is_array($GLOBALS[$currentGrant[0]])
  192. && count($GLOBALS[$currentGrant[0]]) == $_REQUEST['column_count']
  193. && empty($GLOBALS[$currentGrant[0] . '_none']))))
  194. ) {
  195. if ($enableHTML) {
  196. $privs[] = '<dfn title="' . $currentGrant[2] . '">'
  197. . $currentGrant[1] . '</dfn>';
  198. } else {
  199. $privs[] = $currentGrant[1];
  200. }
  201. } elseif (
  202. ! empty($GLOBALS[$currentGrant[0]])
  203. && is_array($GLOBALS[$currentGrant[0]])
  204. && empty($GLOBALS[$currentGrant[0] . '_none'])
  205. ) {
  206. // Required for proper escaping of ` (backtick) in a column name
  207. $grantCols = array_map(
  208. /**
  209. * @param string $val
  210. *
  211. * @return string
  212. */
  213. static function ($val) {
  214. return Util::backquote($val);
  215. },
  216. $GLOBALS[$currentGrant[0]]
  217. );
  218. if ($enableHTML) {
  219. $privs[] = '<dfn title="' . $currentGrant[2] . '">'
  220. . $currentGrant[1] . '</dfn>'
  221. . ' (' . implode(', ', $grantCols) . ')';
  222. } else {
  223. $privs[] = $currentGrant[1]
  224. . ' (' . implode(', ', $grantCols) . ')';
  225. }
  226. } else {
  227. $allPrivileges = false;
  228. }
  229. }
  230. if (empty($privs)) {
  231. if ($enableHTML) {
  232. $privs[] = '<dfn title="' . __('No privileges.') . '">USAGE</dfn>';
  233. } else {
  234. $privs[] = 'USAGE';
  235. }
  236. } elseif ($allPrivileges && (! isset($_POST['grant_count']) || count($privs) == $_POST['grant_count'])) {
  237. if ($enableHTML) {
  238. $privs = [
  239. '<dfn title="'
  240. . __('Includes all privileges except GRANT.')
  241. . '">ALL PRIVILEGES</dfn>',
  242. ];
  243. } else {
  244. $privs = ['ALL PRIVILEGES'];
  245. }
  246. }
  247. return $privs;
  248. }
  249. /**
  250. * Returns an array of table grants and their descriptions
  251. *
  252. * @return array array of table grants
  253. */
  254. public function getTableGrantsArray()
  255. {
  256. return [
  257. [
  258. 'Delete',
  259. 'DELETE',
  260. __('Allows deleting data.'),
  261. ],
  262. [
  263. 'Create',
  264. 'CREATE',
  265. __('Allows creating new tables.'),
  266. ],
  267. [
  268. 'Drop',
  269. 'DROP',
  270. __('Allows dropping tables.'),
  271. ],
  272. [
  273. 'Index',
  274. 'INDEX',
  275. __('Allows creating and dropping indexes.'),
  276. ],
  277. [
  278. 'Alter',
  279. 'ALTER',
  280. __('Allows altering the structure of existing tables.'),
  281. ],
  282. [
  283. 'Create View',
  284. 'CREATE_VIEW',
  285. __('Allows creating new views.'),
  286. ],
  287. [
  288. 'Show view',
  289. 'SHOW_VIEW',
  290. __('Allows performing SHOW CREATE VIEW queries.'),
  291. ],
  292. [
  293. 'Trigger',
  294. 'TRIGGER',
  295. __('Allows creating and dropping triggers.'),
  296. ],
  297. ];
  298. }
  299. /**
  300. * Get the grants array which contains all the privilege types
  301. * and relevant grant messages
  302. *
  303. * @return array
  304. */
  305. public function getGrantsArray()
  306. {
  307. return [
  308. [
  309. 'Select_priv',
  310. 'SELECT',
  311. __('Allows reading data.'),
  312. ],
  313. [
  314. 'Insert_priv',
  315. 'INSERT',
  316. __('Allows inserting and replacing data.'),
  317. ],
  318. [
  319. 'Update_priv',
  320. 'UPDATE',
  321. __('Allows changing data.'),
  322. ],
  323. [
  324. 'Delete_priv',
  325. 'DELETE',
  326. __('Allows deleting data.'),
  327. ],
  328. [
  329. 'Create_priv',
  330. 'CREATE',
  331. __('Allows creating new databases and tables.'),
  332. ],
  333. [
  334. 'Drop_priv',
  335. 'DROP',
  336. __('Allows dropping databases and tables.'),
  337. ],
  338. [
  339. 'Reload_priv',
  340. 'RELOAD',
  341. __('Allows reloading server settings and flushing the server\'s caches.'),
  342. ],
  343. [
  344. 'Shutdown_priv',
  345. 'SHUTDOWN',
  346. __('Allows shutting down the server.'),
  347. ],
  348. [
  349. 'Process_priv',
  350. 'PROCESS',
  351. __('Allows viewing processes of all users.'),
  352. ],
  353. [
  354. 'File_priv',
  355. 'FILE',
  356. __('Allows importing data from and exporting data into files.'),
  357. ],
  358. [
  359. 'References_priv',
  360. 'REFERENCES',
  361. __('Has no effect in this MySQL version.'),
  362. ],
  363. [
  364. 'Index_priv',
  365. 'INDEX',
  366. __('Allows creating and dropping indexes.'),
  367. ],
  368. [
  369. 'Alter_priv',
  370. 'ALTER',
  371. __('Allows altering the structure of existing tables.'),
  372. ],
  373. [
  374. 'Show_db_priv',
  375. 'SHOW DATABASES',
  376. __('Gives access to the complete list of databases.'),
  377. ],
  378. [
  379. 'Super_priv',
  380. 'SUPER',
  381. __(
  382. 'Allows connecting, even if maximum number of connections '
  383. . 'is reached; required for most administrative operations '
  384. . 'like setting global variables or killing threads of other users.'
  385. ),
  386. ],
  387. [
  388. 'Create_tmp_table_priv',
  389. 'CREATE TEMPORARY TABLES',
  390. __('Allows creating temporary tables.'),
  391. ],
  392. [
  393. 'Lock_tables_priv',
  394. 'LOCK TABLES',
  395. __('Allows locking tables for the current thread.'),
  396. ],
  397. [
  398. 'Repl_slave_priv',
  399. 'REPLICATION SLAVE',
  400. __('Needed for the replication slaves.'),
  401. ],
  402. [
  403. 'Repl_client_priv',
  404. 'REPLICATION CLIENT',
  405. __('Allows the user to ask where the slaves / masters are.'),
  406. ],
  407. [
  408. 'Create_view_priv',
  409. 'CREATE VIEW',
  410. __('Allows creating new views.'),
  411. ],
  412. [
  413. 'Event_priv',
  414. 'EVENT',
  415. __('Allows to set up events for the event scheduler.'),
  416. ],
  417. [
  418. 'Trigger_priv',
  419. 'TRIGGER',
  420. __('Allows creating and dropping triggers.'),
  421. ],
  422. // for table privs:
  423. [
  424. 'Create View_priv',
  425. 'CREATE VIEW',
  426. __('Allows creating new views.'),
  427. ],
  428. [
  429. 'Show_view_priv',
  430. 'SHOW VIEW',
  431. __('Allows performing SHOW CREATE VIEW queries.'),
  432. ],
  433. // for table privs:
  434. [
  435. 'Show view_priv',
  436. 'SHOW VIEW',
  437. __('Allows performing SHOW CREATE VIEW queries.'),
  438. ],
  439. [
  440. 'Delete_history_priv',
  441. 'DELETE HISTORY',
  442. // phpcs:ignore Generic.Files.LineLength.TooLong
  443. /* l10n: https://mariadb.com/kb/en/library/grant/#table-privileges "Remove historical rows from a table using the DELETE HISTORY statement" */
  444. __('Allows deleting historical rows.'),
  445. ],
  446. [
  447. // This was finally removed in the following MariaDB versions
  448. // @see https://jira.mariadb.org/browse/MDEV-20382
  449. 'Delete versioning rows_priv',
  450. 'DELETE HISTORY',
  451. // phpcs:ignore Generic.Files.LineLength.TooLong
  452. /* l10n: https://mariadb.com/kb/en/library/grant/#table-privileges "Remove historical rows from a table using the DELETE HISTORY statement" */
  453. __('Allows deleting historical rows.'),
  454. ],
  455. [
  456. 'Create_routine_priv',
  457. 'CREATE ROUTINE',
  458. __('Allows creating stored routines.'),
  459. ],
  460. [
  461. 'Alter_routine_priv',
  462. 'ALTER ROUTINE',
  463. __('Allows altering and dropping stored routines.'),
  464. ],
  465. [
  466. 'Create_user_priv',
  467. 'CREATE USER',
  468. __('Allows creating, dropping and renaming user accounts.'),
  469. ],
  470. [
  471. 'Execute_priv',
  472. 'EXECUTE',
  473. __('Allows executing stored routines.'),
  474. ],
  475. ];
  476. }
  477. /**
  478. * Get sql query for display privileges table
  479. *
  480. * @param string $db the database
  481. * @param string $table the table
  482. * @param string $username username for database connection
  483. * @param string $hostname hostname for database connection
  484. *
  485. * @return string sql query
  486. */
  487. public function getSqlQueryForDisplayPrivTable($db, $table, $username, $hostname)
  488. {
  489. if ($db === '*') {
  490. return 'SELECT * FROM `mysql`.`user`'
  491. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  492. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "';";
  493. }
  494. if ($table === '*') {
  495. return 'SELECT * FROM `mysql`.`db`'
  496. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  497. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "'"
  498. . " AND `Db` = '" . $this->dbi->escapeString($db) . "'";
  499. }
  500. return 'SELECT `Table_priv`'
  501. . ' FROM `mysql`.`tables_priv`'
  502. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  503. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "'"
  504. . " AND `Db` = '" . $this->dbi->escapeString(Util::unescapeMysqlWildcards($db)) . "'"
  505. . " AND `Table_name` = '" . $this->dbi->escapeString($table) . "';";
  506. }
  507. /**
  508. * Sets the user group from request values
  509. *
  510. * @param string $username username
  511. * @param string $userGroup user group to set
  512. */
  513. public function setUserGroup($username, $userGroup): void
  514. {
  515. $userGroup = $userGroup ?? '';
  516. $cfgRelation = $this->relation->getRelationsParam();
  517. if (empty($cfgRelation['db']) || empty($cfgRelation['users']) || empty($cfgRelation['usergroups'])) {
  518. return;
  519. }
  520. $userTable = Util::backquote($cfgRelation['db'])
  521. . '.' . Util::backquote($cfgRelation['users']);
  522. $sqlQuery = 'SELECT `usergroup` FROM ' . $userTable
  523. . " WHERE `username` = '" . $this->dbi->escapeString($username) . "'";
  524. $oldUserGroup = $this->dbi->fetchValue($sqlQuery, 0, 0, DatabaseInterface::CONNECT_CONTROL);
  525. if ($oldUserGroup === false) {
  526. $updQuery = 'INSERT INTO ' . $userTable . '(`username`, `usergroup`)'
  527. . " VALUES ('" . $this->dbi->escapeString($username) . "', "
  528. . "'" . $this->dbi->escapeString($userGroup) . "')";
  529. } else {
  530. if (empty($userGroup)) {
  531. $updQuery = 'DELETE FROM ' . $userTable
  532. . " WHERE `username`='" . $this->dbi->escapeString($username) . "'";
  533. } elseif ($oldUserGroup != $userGroup) {
  534. $updQuery = 'UPDATE ' . $userTable
  535. . " SET `usergroup`='" . $this->dbi->escapeString($userGroup) . "'"
  536. . " WHERE `username`='" . $this->dbi->escapeString($username) . "'";
  537. }
  538. }
  539. if (! isset($updQuery)) {
  540. return;
  541. }
  542. $this->relation->queryAsControlUser($updQuery);
  543. }
  544. /**
  545. * Displays the privileges form table
  546. *
  547. * @param string $db the database
  548. * @param string $table the table
  549. * @param bool $submit whether to display the submit button or not
  550. *
  551. * @return string html snippet
  552. *
  553. * @global array $cfg the phpMyAdmin configuration
  554. * @global resource $user_link the database connection
  555. */
  556. public function getHtmlToDisplayPrivilegesTable(
  557. $db = '*',
  558. $table = '*',
  559. $submit = true
  560. ) {
  561. $sqlQuery = '';
  562. if ($db === '*') {
  563. $table = '*';
  564. }
  565. $username = '';
  566. $hostname = '';
  567. $row = [];
  568. if (isset($GLOBALS['username'])) {
  569. $username = $GLOBALS['username'];
  570. $hostname = $GLOBALS['hostname'];
  571. $sqlQuery = $this->getSqlQueryForDisplayPrivTable($db, $table, $username, $hostname);
  572. $row = $this->dbi->fetchSingleRow($sqlQuery);
  573. }
  574. if (empty($row)) {
  575. if ($table === '*' && $this->dbi->isSuperUser()) {
  576. $row = [];
  577. if ($db === '*') {
  578. $sqlQuery = 'SHOW COLUMNS FROM `mysql`.`user`;';
  579. } elseif ($table === '*') {
  580. $sqlQuery = 'SHOW COLUMNS FROM `mysql`.`db`;';
  581. }
  582. $res = $this->dbi->query($sqlQuery);
  583. while ($row1 = $this->dbi->fetchRow($res)) {
  584. if (mb_substr($row1[0], 0, 4) === 'max_') {
  585. $row[$row1[0]] = 0;
  586. } elseif (mb_substr($row1[0], 0, 5) === 'x509_' || mb_substr($row1[0], 0, 4) === 'ssl_') {
  587. $row[$row1[0]] = '';
  588. } else {
  589. $row[$row1[0]] = 'N';
  590. }
  591. }
  592. $this->dbi->freeResult($res);
  593. } elseif ($table === '*') {
  594. $row = [];
  595. } else {
  596. $row = ['Table_priv' => ''];
  597. }
  598. }
  599. if (isset($row['Table_priv'])) {
  600. $this->fillInTablePrivileges($row);
  601. // get columns
  602. $res = $this->dbi->tryQuery(
  603. 'SHOW COLUMNS FROM '
  604. . Util::backquote(
  605. Util::unescapeMysqlWildcards($db)
  606. )
  607. . '.' . Util::backquote($table) . ';'
  608. );
  609. $columns = [];
  610. if ($res) {
  611. while ($row1 = $this->dbi->fetchRow($res)) {
  612. $columns[$row1[0]] = [
  613. 'Select' => false,
  614. 'Insert' => false,
  615. 'Update' => false,
  616. 'References' => false,
  617. ];
  618. }
  619. $this->dbi->freeResult($res);
  620. }
  621. }
  622. if (! empty($columns)) {
  623. $res = $this->dbi->query(
  624. 'SELECT `Column_name`, `Column_priv`'
  625. . ' FROM `mysql`.`columns_priv`'
  626. . ' WHERE `User`'
  627. . ' = \'' . $this->dbi->escapeString($username) . "'"
  628. . ' AND `Host`'
  629. . ' = \'' . $this->dbi->escapeString($hostname) . "'"
  630. . ' AND `Db`'
  631. . ' = \'' . $this->dbi->escapeString(
  632. Util::unescapeMysqlWildcards($db)
  633. ) . "'"
  634. . ' AND `Table_name`'
  635. . ' = \'' . $this->dbi->escapeString($table) . '\';'
  636. );
  637. while ($row1 = $this->dbi->fetchRow($res)) {
  638. $row1[1] = explode(',', $row1[1]);
  639. foreach ($row1[1] as $current) {
  640. $columns[$row1[0]][$current] = true;
  641. }
  642. }
  643. $this->dbi->freeResult($res);
  644. }
  645. return $this->template->render('server/privileges/privileges_table', [
  646. 'is_global' => $db === '*',
  647. 'is_database' => $table === '*',
  648. 'row' => $row,
  649. 'columns' => $columns ?? [],
  650. 'has_submit' => $submit,
  651. 'supports_references_privilege' => Compatibility::supportsReferencesPrivilege($this->dbi),
  652. 'is_mariadb' => $this->dbi->isMariaDB(),
  653. ]);
  654. }
  655. /**
  656. * Get the HTML snippet for routine specific privileges
  657. *
  658. * @param string $username username for database connection
  659. * @param string $hostname hostname for database connection
  660. * @param string $db the database
  661. * @param string $routine the routine
  662. * @param string $urlDbname url encoded db name
  663. *
  664. * @return string
  665. */
  666. public function getHtmlForRoutineSpecificPrivileges(
  667. $username,
  668. $hostname,
  669. $db,
  670. $routine,
  671. $urlDbname
  672. ) {
  673. $privileges = $this->getRoutinePrivileges($username, $hostname, $db, $routine);
  674. return $this->template->render('server/privileges/edit_routine_privileges', [
  675. 'username' => $username,
  676. 'hostname' => $hostname,
  677. 'database' => $db,
  678. 'routine' => $routine,
  679. 'privileges' => $privileges,
  680. 'dbname' => $urlDbname,
  681. 'current_user' => $this->dbi->getCurrentUser(),
  682. ]);
  683. }
  684. /**
  685. * Displays the fields used by the "new user" form as well as the
  686. * "change login information / copy user" form.
  687. *
  688. * @param string $mode are we creating a new user or are we just
  689. * changing one? (allowed values: 'new', 'change')
  690. * @param string $user User name
  691. * @param string $host Host name
  692. *
  693. * @return string a HTML snippet
  694. */
  695. public function getHtmlForLoginInformationFields(
  696. $mode = 'new',
  697. $user = null,
  698. $host = null
  699. ) {
  700. global $pred_username, $pred_hostname, $username, $hostname, $new_username;
  701. [$usernameLength, $hostnameLength] = $this->getUsernameAndHostnameLength();
  702. if (isset($username) && strlen($username) === 0) {
  703. $pred_username = 'any';
  704. }
  705. $currentUser = $this->dbi->fetchValue('SELECT USER();');
  706. $thisHost = null;
  707. if (! empty($currentUser)) {
  708. $thisHost = str_replace(
  709. '\'',
  710. '',
  711. mb_substr(
  712. $currentUser,
  713. mb_strrpos($currentUser, '@') + 1
  714. )
  715. );
  716. }
  717. if (! isset($pred_hostname) && isset($hostname)) {
  718. switch (mb_strtolower($hostname)) {
  719. case 'localhost':
  720. case '127.0.0.1':
  721. $pred_hostname = 'localhost';
  722. break;
  723. case '%':
  724. $pred_hostname = 'any';
  725. break;
  726. default:
  727. $pred_hostname = 'userdefined';
  728. break;
  729. }
  730. }
  731. $serverVersion = $this->dbi->getVersion();
  732. $authPlugin = $this->getCurrentAuthenticationPlugin($mode, $user, $host);
  733. $isNew = (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50507)
  734. || (Compatibility::isMariaDb() && $serverVersion >= 50200);
  735. $activeAuthPlugins = ['mysql_native_password' => __('Native MySQL authentication')];
  736. if ($isNew) {
  737. $activeAuthPlugins = $this->plugins->getAuthentication();
  738. if (isset($activeAuthPlugins['mysql_old_password'])) {
  739. unset($activeAuthPlugins['mysql_old_password']);
  740. }
  741. }
  742. return $this->template->render('server/privileges/login_information_fields', [
  743. 'pred_username' => $pred_username ?? null,
  744. 'pred_hostname' => $pred_hostname ?? null,
  745. 'username_length' => $usernameLength,
  746. 'hostname_length' => $hostnameLength,
  747. 'username' => $username ?? null,
  748. 'new_username' => $new_username ?? null,
  749. 'hostname' => $hostname ?? null,
  750. 'this_host' => $thisHost,
  751. 'is_change' => $mode === 'change',
  752. 'auth_plugin' => $authPlugin,
  753. 'active_auth_plugins' => $activeAuthPlugins,
  754. 'is_new' => $isNew,
  755. ]);
  756. }
  757. /**
  758. * Get username and hostname length
  759. *
  760. * @return array username length and hostname length
  761. */
  762. public function getUsernameAndHostnameLength()
  763. {
  764. /* Fallback values */
  765. $usernameLength = 16;
  766. $hostnameLength = 41;
  767. /* Try to get real lengths from the database */
  768. $fieldsInfo = $this->dbi->fetchResult(
  769. 'SELECT COLUMN_NAME, CHARACTER_MAXIMUM_LENGTH '
  770. . 'FROM information_schema.columns '
  771. . "WHERE table_schema = 'mysql' AND table_name = 'user' "
  772. . "AND COLUMN_NAME IN ('User', 'Host')"
  773. );
  774. foreach ($fieldsInfo as $val) {
  775. if ($val['COLUMN_NAME'] === 'User') {
  776. $usernameLength = $val['CHARACTER_MAXIMUM_LENGTH'];
  777. } elseif ($val['COLUMN_NAME'] === 'Host') {
  778. $hostnameLength = $val['CHARACTER_MAXIMUM_LENGTH'];
  779. }
  780. }
  781. return [
  782. $usernameLength,
  783. $hostnameLength,
  784. ];
  785. }
  786. /**
  787. * Get current authentication plugin in use - for a user or globally
  788. *
  789. * @param string $mode are we creating a new user or are we just
  790. * changing one? (allowed values: 'new', 'change')
  791. * @param string $username User name
  792. * @param string $hostname Host name
  793. *
  794. * @return string authentication plugin in use
  795. */
  796. public function getCurrentAuthenticationPlugin(
  797. $mode = 'new',
  798. $username = null,
  799. $hostname = null
  800. ) {
  801. global $dbi;
  802. /* Fallback (standard) value */
  803. $authenticationPlugin = 'mysql_native_password';
  804. $serverVersion = $this->dbi->getVersion();
  805. if (isset($username, $hostname) && $mode === 'change') {
  806. $row = $this->dbi->fetchSingleRow(
  807. 'SELECT `plugin` FROM `mysql`.`user` WHERE `User` = "'
  808. . $dbi->escapeString($username)
  809. . '" AND `Host` = "'
  810. . $dbi->escapeString($hostname)
  811. . '" LIMIT 1'
  812. );
  813. // Table 'mysql'.'user' may not exist for some previous
  814. // versions of MySQL - in that case consider fallback value
  815. if (is_array($row) && isset($row['plugin'])) {
  816. $authenticationPlugin = $row['plugin'];
  817. }
  818. } elseif ($mode === 'change') {
  819. [$username, $hostname] = $this->dbi->getCurrentUserAndHost();
  820. $row = $this->dbi->fetchSingleRow(
  821. 'SELECT `plugin` FROM `mysql`.`user` WHERE `User` = "'
  822. . $dbi->escapeString($username)
  823. . '" AND `Host` = "'
  824. . $dbi->escapeString($hostname)
  825. . '"'
  826. );
  827. if (is_array($row) && isset($row['plugin'])) {
  828. $authenticationPlugin = $row['plugin'];
  829. }
  830. } elseif ($serverVersion >= 50702) {
  831. $row = $this->dbi->fetchSingleRow('SELECT @@default_authentication_plugin');
  832. $authenticationPlugin = is_array($row) ? $row['@@default_authentication_plugin'] : null;
  833. }
  834. return $authenticationPlugin;
  835. }
  836. /**
  837. * Returns all the grants for a certain user on a certain host
  838. * Used in the export privileges for all users section
  839. *
  840. * @param string $user User name
  841. * @param string $host Host name
  842. *
  843. * @return string containing all the grants text
  844. */
  845. public function getGrants($user, $host)
  846. {
  847. $grants = $this->dbi->fetchResult(
  848. "SHOW GRANTS FOR '"
  849. . $this->dbi->escapeString($user) . "'@'"
  850. . $this->dbi->escapeString($host) . "'"
  851. );
  852. $response = '';
  853. foreach ($grants as $oneGrant) {
  854. $response .= $oneGrant . ";\n\n";
  855. }
  856. return $response;
  857. }
  858. /**
  859. * Update password and get message for password updating
  860. *
  861. * @param string $errorUrl error url
  862. * @param string $username username
  863. * @param string $hostname hostname
  864. *
  865. * @return Message success or error message after updating password
  866. */
  867. public function updatePassword($errorUrl, $username, $hostname)
  868. {
  869. global $dbi;
  870. // similar logic in /user-password
  871. $message = null;
  872. if (isset($_POST['pma_pw'], $_POST['pma_pw2']) && empty($_POST['nopass'])) {
  873. if ($_POST['pma_pw'] != $_POST['pma_pw2']) {
  874. $message = Message::error(__('The passwords aren\'t the same!'));
  875. } elseif (empty($_POST['pma_pw']) || empty($_POST['pma_pw2'])) {
  876. $message = Message::error(__('The password is empty!'));
  877. }
  878. }
  879. // here $nopass could be == 1
  880. if ($message === null) {
  881. $hashingFunction = 'PASSWORD';
  882. $serverVersion = $this->dbi->getVersion();
  883. $authenticationPlugin = ($_POST['authentication_plugin'] ?? $this->getCurrentAuthenticationPlugin(
  884. 'change',
  885. $username,
  886. $hostname
  887. ));
  888. // Use 'ALTER USER ...' syntax for MySQL 5.7.6+
  889. if (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50706) {
  890. if ($authenticationPlugin !== 'mysql_old_password') {
  891. $queryPrefix = "ALTER USER '"
  892. . $this->dbi->escapeString($username)
  893. . "'@'" . $this->dbi->escapeString($hostname) . "'"
  894. . ' IDENTIFIED WITH '
  895. . $authenticationPlugin
  896. . " BY '";
  897. } else {
  898. $queryPrefix = "ALTER USER '"
  899. . $this->dbi->escapeString($username)
  900. . "'@'" . $this->dbi->escapeString($hostname) . "'"
  901. . " IDENTIFIED BY '";
  902. }
  903. // in $sql_query which will be displayed, hide the password
  904. $sqlQuery = $queryPrefix . "*'";
  905. $localQuery = $queryPrefix
  906. . $this->dbi->escapeString($_POST['pma_pw']) . "'";
  907. } elseif (Compatibility::isMariaDb() && $serverVersion >= 10000) {
  908. // MariaDB uses "SET PASSWORD" syntax to change user password.
  909. // On Galera cluster only DDL queries are replicated, since
  910. // users are stored in MyISAM storage engine.
  911. $queryPrefix = "SET PASSWORD FOR '"
  912. . $this->dbi->escapeString($username)
  913. . "'@'" . $this->dbi->escapeString($hostname) . "'"
  914. . " = PASSWORD ('";
  915. $sqlQuery = $localQuery = $queryPrefix
  916. . $this->dbi->escapeString($_POST['pma_pw']) . "')";
  917. } elseif (Compatibility::isMariaDb() && $serverVersion >= 50200 && $this->dbi->isSuperUser()) {
  918. // Use 'UPDATE `mysql`.`user` ...' Syntax for MariaDB 5.2+
  919. if ($authenticationPlugin === 'mysql_native_password') {
  920. // Set the hashing method used by PASSWORD()
  921. // to be 'mysql_native_password' type
  922. $this->dbi->tryQuery('SET old_passwords = 0;');
  923. } elseif ($authenticationPlugin === 'sha256_password') {
  924. // Set the hashing method used by PASSWORD()
  925. // to be 'sha256_password' type
  926. $this->dbi->tryQuery('SET `old_passwords` = 2;');
  927. }
  928. $hashedPassword = $this->getHashedPassword($_POST['pma_pw']);
  929. $sqlQuery = 'SET PASSWORD FOR \''
  930. . $this->dbi->escapeString($username)
  931. . '\'@\'' . $this->dbi->escapeString($hostname) . '\' = '
  932. . ($_POST['pma_pw'] == ''
  933. ? '\'\''
  934. : $hashingFunction . '(\''
  935. . preg_replace('@.@s', '*', $_POST['pma_pw']) . '\')');
  936. $localQuery = 'UPDATE `mysql`.`user` SET '
  937. . " `authentication_string` = '" . $hashedPassword
  938. . "', `Password` = '', "
  939. . " `plugin` = '" . $authenticationPlugin . "'"
  940. . " WHERE `User` = '" . $dbi->escapeString($username)
  941. . "' AND Host = '" . $dbi->escapeString($hostname) . "';";
  942. } else {
  943. // USE 'SET PASSWORD ...' syntax for rest of the versions
  944. // Backup the old value, to be reset later
  945. $row = $this->dbi->fetchSingleRow('SELECT @@old_passwords;');
  946. $origValue = $row['@@old_passwords'];
  947. $updatePluginQuery = 'UPDATE `mysql`.`user` SET'
  948. . " `plugin` = '" . $authenticationPlugin . "'"
  949. . " WHERE `User` = '" . $dbi->escapeString($username)
  950. . "' AND Host = '" . $dbi->escapeString($hostname) . "';";
  951. // Update the plugin for the user
  952. if (! $this->dbi->tryQuery($updatePluginQuery)) {
  953. Generator::mysqlDie(
  954. $this->dbi->getError(),
  955. $updatePluginQuery,
  956. false,
  957. $errorUrl
  958. );
  959. }
  960. $this->dbi->tryQuery('FLUSH PRIVILEGES;');
  961. if ($authenticationPlugin === 'mysql_native_password') {
  962. // Set the hashing method used by PASSWORD()
  963. // to be 'mysql_native_password' type
  964. $this->dbi->tryQuery('SET old_passwords = 0;');
  965. } elseif ($authenticationPlugin === 'sha256_password') {
  966. // Set the hashing method used by PASSWORD()
  967. // to be 'sha256_password' type
  968. $this->dbi->tryQuery('SET `old_passwords` = 2;');
  969. }
  970. $sqlQuery = 'SET PASSWORD FOR \''
  971. . $this->dbi->escapeString($username)
  972. . '\'@\'' . $this->dbi->escapeString($hostname) . '\' = '
  973. . ($_POST['pma_pw'] == ''
  974. ? '\'\''
  975. : $hashingFunction . '(\''
  976. . preg_replace('@.@s', '*', $_POST['pma_pw']) . '\')');
  977. $localQuery = 'SET PASSWORD FOR \''
  978. . $this->dbi->escapeString($username)
  979. . '\'@\'' . $this->dbi->escapeString($hostname) . '\' = '
  980. . ($_POST['pma_pw'] == '' ? '\'\'' : $hashingFunction
  981. . '(\'' . $this->dbi->escapeString($_POST['pma_pw']) . '\')');
  982. }
  983. if (! $this->dbi->tryQuery($localQuery)) {
  984. Generator::mysqlDie(
  985. $this->dbi->getError(),
  986. $sqlQuery,
  987. false,
  988. $errorUrl
  989. );
  990. }
  991. // Flush privileges after successful password change
  992. $this->dbi->tryQuery('FLUSH PRIVILEGES;');
  993. $message = Message::success(
  994. __('The password for %s was changed successfully.')
  995. );
  996. $message->addParam('\'' . $username . '\'@\'' . $hostname . '\'');
  997. if (isset($origValue)) {
  998. $this->dbi->tryQuery('SET `old_passwords` = ' . $origValue . ';');
  999. }
  1000. }
  1001. return $message;
  1002. }
  1003. /**
  1004. * Revokes privileges and get message and SQL query for privileges revokes
  1005. *
  1006. * @param string $dbname database name
  1007. * @param string $tablename table name
  1008. * @param string $username username
  1009. * @param string $hostname host name
  1010. * @param string $itemType item type
  1011. *
  1012. * @return array ($message, $sql_query)
  1013. */
  1014. public function getMessageAndSqlQueryForPrivilegesRevoke(
  1015. string $dbname,
  1016. string $tablename,
  1017. $username,
  1018. $hostname,
  1019. $itemType
  1020. ) {
  1021. $dbAndTable = $this->wildcardEscapeForGrant($dbname, $tablename);
  1022. $sqlQuery0 = 'REVOKE ALL PRIVILEGES ON ' . $itemType . ' ' . $dbAndTable
  1023. . ' FROM \''
  1024. . $this->dbi->escapeString($username) . '\'@\''
  1025. . $this->dbi->escapeString($hostname) . '\';';
  1026. $sqlQuery1 = 'REVOKE GRANT OPTION ON ' . $itemType . ' ' . $dbAndTable
  1027. . ' FROM \'' . $this->dbi->escapeString($username) . '\'@\''
  1028. . $this->dbi->escapeString($hostname) . '\';';
  1029. $this->dbi->query($sqlQuery0);
  1030. if (! $this->dbi->tryQuery($sqlQuery1)) {
  1031. // this one may fail, too...
  1032. $sqlQuery1 = '';
  1033. }
  1034. $sqlQuery = $sqlQuery0 . ' ' . $sqlQuery1;
  1035. $message = Message::success(
  1036. __('You have revoked the privileges for %s.')
  1037. );
  1038. $message->addParam('\'' . $username . '\'@\'' . $hostname . '\'');
  1039. return [
  1040. $message,
  1041. $sqlQuery,
  1042. ];
  1043. }
  1044. /**
  1045. * Get REQUIRE clause
  1046. *
  1047. * @return string REQUIRE clause
  1048. */
  1049. public function getRequireClause()
  1050. {
  1051. $arr = isset($_POST['ssl_type']) ? $_POST : $GLOBALS;
  1052. if (isset($arr['ssl_type']) && $arr['ssl_type'] === 'SPECIFIED') {
  1053. $require = [];
  1054. if (! empty($arr['ssl_cipher'])) {
  1055. $require[] = "CIPHER '"
  1056. . $this->dbi->escapeString($arr['ssl_cipher']) . "'";
  1057. }
  1058. if (! empty($arr['x509_issuer'])) {
  1059. $require[] = "ISSUER '"
  1060. . $this->dbi->escapeString($arr['x509_issuer']) . "'";
  1061. }
  1062. if (! empty($arr['x509_subject'])) {
  1063. $require[] = "SUBJECT '"
  1064. . $this->dbi->escapeString($arr['x509_subject']) . "'";
  1065. }
  1066. if (count($require)) {
  1067. $requireClause = ' REQUIRE ' . implode(' AND ', $require);
  1068. } else {
  1069. $requireClause = ' REQUIRE NONE';
  1070. }
  1071. } elseif (isset($arr['ssl_type']) && $arr['ssl_type'] === 'X509') {
  1072. $requireClause = ' REQUIRE X509';
  1073. } elseif (isset($arr['ssl_type']) && $arr['ssl_type'] === 'ANY') {
  1074. $requireClause = ' REQUIRE SSL';
  1075. } else {
  1076. $requireClause = ' REQUIRE NONE';
  1077. }
  1078. return $requireClause;
  1079. }
  1080. /**
  1081. * Get a WITH clause for 'update privileges' and 'add user'
  1082. *
  1083. * @return string
  1084. */
  1085. public function getWithClauseForAddUserAndUpdatePrivs()
  1086. {
  1087. $sqlQuery = '';
  1088. if (
  1089. ((isset($_POST['Grant_priv']) && $_POST['Grant_priv'] === 'Y')
  1090. || (isset($GLOBALS['Grant_priv']) && $GLOBALS['Grant_priv'] === 'Y'))
  1091. && ! (Compatibility::isMySqlOrPerconaDb() && $this->dbi->getVersion() >= 80011)
  1092. ) {
  1093. $sqlQuery .= ' GRANT OPTION';
  1094. }
  1095. if (isset($_POST['max_questions']) || isset($GLOBALS['max_questions'])) {
  1096. $maxQuestions = isset($_POST['max_questions'])
  1097. ? (int) $_POST['max_questions'] : (int) $GLOBALS['max_questions'];
  1098. $maxQuestions = max(0, $maxQuestions);
  1099. $sqlQuery .= ' MAX_QUERIES_PER_HOUR ' . $maxQuestions;
  1100. }
  1101. if (isset($_POST['max_connections']) || isset($GLOBALS['max_connections'])) {
  1102. $maxConnections = isset($_POST['max_connections'])
  1103. ? (int) $_POST['max_connections'] : (int) $GLOBALS['max_connections'];
  1104. $maxConnections = max(0, $maxConnections);
  1105. $sqlQuery .= ' MAX_CONNECTIONS_PER_HOUR ' . $maxConnections;
  1106. }
  1107. if (isset($_POST['max_updates']) || isset($GLOBALS['max_updates'])) {
  1108. $maxUpdates = isset($_POST['max_updates'])
  1109. ? (int) $_POST['max_updates'] : (int) $GLOBALS['max_updates'];
  1110. $maxUpdates = max(0, $maxUpdates);
  1111. $sqlQuery .= ' MAX_UPDATES_PER_HOUR ' . $maxUpdates;
  1112. }
  1113. if (isset($_POST['max_user_connections']) || isset($GLOBALS['max_user_connections'])) {
  1114. $maxUserConnections = isset($_POST['max_user_connections'])
  1115. ? (int) $_POST['max_user_connections']
  1116. : (int) $GLOBALS['max_user_connections'];
  1117. $maxUserConnections = max(0, $maxUserConnections);
  1118. $sqlQuery .= ' MAX_USER_CONNECTIONS ' . $maxUserConnections;
  1119. }
  1120. return ! empty($sqlQuery) ? ' WITH' . $sqlQuery : '';
  1121. }
  1122. /**
  1123. * Get HTML for addUsersForm, This function call if isset($_GET['adduser'])
  1124. *
  1125. * @param string $dbname database name
  1126. *
  1127. * @return string HTML for addUserForm
  1128. */
  1129. public function getHtmlForAddUser($dbname)
  1130. {
  1131. $isGrantUser = $this->dbi->isGrantUser();
  1132. $loginInformationFieldsNew = $this->getHtmlForLoginInformationFields('new');
  1133. $privilegesTable = '';
  1134. if ($isGrantUser) {
  1135. $privilegesTable = $this->getHtmlToDisplayPrivilegesTable('*', '*', false);
  1136. }
  1137. return $this->template->render('server/privileges/add_user', [
  1138. 'database' => $dbname,
  1139. 'login_information_fields_new' => $loginInformationFieldsNew,
  1140. 'is_grant_user' => $isGrantUser,
  1141. 'privileges_table' => $privilegesTable,
  1142. ]);
  1143. }
  1144. /**
  1145. * @param string $db database name
  1146. * @param string $table table name
  1147. *
  1148. * @return array
  1149. */
  1150. public function getAllPrivileges(string $db, string $table = ''): array
  1151. {
  1152. $databasePrivileges = $this->getGlobalAndDatabasePrivileges($db);
  1153. $tablePrivileges = [];
  1154. if ($table !== '') {
  1155. $tablePrivileges = $this->getTablePrivileges($db, $table);
  1156. }
  1157. $routinePrivileges = $this->getRoutinesPrivileges($db);
  1158. $allPrivileges = array_merge($databasePrivileges, $tablePrivileges, $routinePrivileges);
  1159. $privileges = [];
  1160. foreach ($allPrivileges as $privilege) {
  1161. $userHost = $privilege['User'] . '@' . $privilege['Host'];
  1162. $privileges[$userHost] = $privileges[$userHost] ?? [];
  1163. $privileges[$userHost]['user'] = (string) $privilege['User'];
  1164. $privileges[$userHost]['host'] = (string) $privilege['Host'];
  1165. $privileges[$userHost]['privileges'] = $privileges[$userHost]['privileges'] ?? [];
  1166. $privileges[$userHost]['privileges'][] = $this->getSpecificPrivilege($privilege);
  1167. }
  1168. return $privileges;
  1169. }
  1170. /**
  1171. * @param array $row Array with user privileges
  1172. *
  1173. * @return array
  1174. */
  1175. private function getSpecificPrivilege(array $row): array
  1176. {
  1177. $privilege = [
  1178. 'type' => $row['Type'],
  1179. 'database' => $row['Db'],
  1180. ];
  1181. if ($row['Type'] === 'r') {
  1182. $privilege['routine'] = $row['Routine_name'];
  1183. $privilege['has_grant'] = str_contains($row['Proc_priv'], 'Grant');
  1184. $privilege['privileges'] = explode(',', $row['Proc_priv']);
  1185. } elseif ($row['Type'] === 't') {
  1186. $privilege['table'] = $row['Table_name'];
  1187. $privilege['has_grant'] = str_contains($row['Table_priv'], 'Grant');
  1188. $tablePrivs = explode(',', $row['Table_priv']);
  1189. $specificPrivileges = [];
  1190. $grantsArr = $this->getTableGrantsArray();
  1191. foreach ($grantsArr as $grant) {
  1192. $specificPrivileges[$grant[0]] = 'N';
  1193. foreach ($tablePrivs as $tablePriv) {
  1194. if ($grant[0] != $tablePriv) {
  1195. continue;
  1196. }
  1197. $specificPrivileges[$grant[0]] = 'Y';
  1198. }
  1199. }
  1200. $privilege['privileges'] = $this->extractPrivInfo($specificPrivileges, true, true);
  1201. } else {
  1202. $privilege['has_grant'] = $row['Grant_priv'] === 'Y';
  1203. $privilege['privileges'] = $this->extractPrivInfo($row, true);
  1204. }
  1205. return $privilege;
  1206. }
  1207. /**
  1208. * @param string $db database name
  1209. *
  1210. * @return array
  1211. */
  1212. private function getGlobalAndDatabasePrivileges(string $db): array
  1213. {
  1214. $listOfPrivileges = '`Select_priv`,
  1215. `Insert_priv`,
  1216. `Update_priv`,
  1217. `Delete_priv`,
  1218. `Create_priv`,
  1219. `Drop_priv`,
  1220. `Grant_priv`,
  1221. `Index_priv`,
  1222. `Alter_priv`,
  1223. `References_priv`,
  1224. `Create_tmp_table_priv`,
  1225. `Lock_tables_priv`,
  1226. `Create_view_priv`,
  1227. `Show_view_priv`,
  1228. `Create_routine_priv`,
  1229. `Alter_routine_priv`,
  1230. `Execute_priv`,
  1231. `Event_priv`,
  1232. `Trigger_priv`,';
  1233. $listOfComparedPrivileges = 'BINARY `Select_priv` = \'N\' AND
  1234. BINARY `Insert_priv` = \'N\' AND
  1235. BINARY `Update_priv` = \'N\' AND
  1236. BINARY `Delete_priv` = \'N\' AND
  1237. BINARY `Create_priv` = \'N\' AND
  1238. BINARY `Drop_priv` = \'N\' AND
  1239. BINARY `Grant_priv` = \'N\' AND
  1240. BINARY `References_priv` = \'N\' AND
  1241. BINARY `Create_tmp_table_priv` = \'N\' AND
  1242. BINARY `Lock_tables_priv` = \'N\' AND
  1243. BINARY `Create_view_priv` = \'N\' AND
  1244. BINARY `Show_view_priv` = \'N\' AND
  1245. BINARY `Create_routine_priv` = \'N\' AND
  1246. BINARY `Alter_routine_priv` = \'N\' AND
  1247. BINARY `Execute_priv` = \'N\' AND
  1248. BINARY `Event_priv` = \'N\' AND
  1249. BINARY `Trigger_priv` = \'N\'';
  1250. $query = '
  1251. (
  1252. SELECT `User`, `Host`, ' . $listOfPrivileges . ' \'*\' AS `Db`, \'g\' AS `Type`
  1253. FROM `mysql`.`user`
  1254. WHERE NOT (' . $listOfComparedPrivileges . ')
  1255. )
  1256. UNION
  1257. (
  1258. SELECT `User`, `Host`, ' . $listOfPrivileges . ' `Db`, \'d\' AS `Type`
  1259. FROM `mysql`.`db`
  1260. WHERE \'' . $this->dbi->escapeString($db) . '\' LIKE `Db` AND NOT (' . $listOfComparedPrivileges . ')
  1261. )
  1262. ORDER BY `User` ASC, `Host` ASC, `Db` ASC;
  1263. ';
  1264. $result = $this->dbi->query($query);
  1265. if ($result === false) {
  1266. return [];
  1267. }
  1268. $privileges = [];
  1269. while ($row = $this->dbi->fetchAssoc($result)) {
  1270. $privileges[] = $row;
  1271. }
  1272. return $privileges;
  1273. }
  1274. /**
  1275. * @param string $db database name
  1276. * @param string $table table name
  1277. *
  1278. * @return array
  1279. */
  1280. private function getTablePrivileges(string $db, string $table): array
  1281. {
  1282. $query = '
  1283. SELECT `User`, `Host`, `Db`, \'t\' AS `Type`, `Table_name`, `Table_priv`
  1284. FROM `mysql`.`tables_priv`
  1285. WHERE
  1286. ? LIKE `Db` AND
  1287. ? LIKE `Table_name` AND
  1288. NOT (`Table_priv` = \'\' AND Column_priv = \'\')
  1289. ORDER BY `User` ASC, `Host` ASC, `Db` ASC, `Table_priv` ASC;
  1290. ';
  1291. /** @var mysqli_stmt|false $statement */
  1292. $statement = $this->dbi->prepare($query);
  1293. if ($statement === false || ! $statement->bind_param('ss', $db, $table) || ! $statement->execute()) {
  1294. return [];
  1295. }
  1296. $result = $statement->get_result();
  1297. $statement->close();
  1298. if ($result === false) {
  1299. return [];
  1300. }
  1301. $privileges = [];
  1302. while ($row = $this->dbi->fetchAssoc($result)) {
  1303. $privileges[] = $row;
  1304. }
  1305. return $privileges;
  1306. }
  1307. /**
  1308. * @param string $db database name
  1309. *
  1310. * @return array
  1311. */
  1312. private function getRoutinesPrivileges(string $db): array
  1313. {
  1314. $query = '
  1315. SELECT *, \'r\' AS `Type`
  1316. FROM `mysql`.`procs_priv`
  1317. WHERE Db = \'' . $this->dbi->escapeString($db) . '\';
  1318. ';
  1319. $result = $this->dbi->query($query);
  1320. if ($result === false) {
  1321. return [];
  1322. }
  1323. $privileges = [];
  1324. while ($row = $this->dbi->fetchAssoc($result)) {
  1325. $privileges[] = $row;
  1326. }
  1327. return $privileges;
  1328. }
  1329. /**
  1330. * Get HTML error for View Users form
  1331. * For non superusers such as grant/create users
  1332. *
  1333. * @return string
  1334. */
  1335. public function getHtmlForViewUsersError()
  1336. {
  1337. return Message::error(
  1338. __('Not enough privilege to view users.')
  1339. )->getDisplay();
  1340. }
  1341. /**
  1342. * Returns edit, revoke or export link for a user.
  1343. *
  1344. * @param string $linktype The link type (edit | revoke | export)
  1345. * @param string $username User name
  1346. * @param string $hostname Host name
  1347. * @param string $dbname Database name
  1348. * @param string $tablename Table name
  1349. * @param string $routinename Routine name
  1350. * @param string $initial Initial value
  1351. *
  1352. * @return string HTML code with link
  1353. */
  1354. public function getUserLink(
  1355. $linktype,
  1356. $username,
  1357. $hostname,
  1358. $dbname = '',
  1359. $tablename = '',
  1360. $routinename = '',
  1361. $initial = ''
  1362. ) {
  1363. $linkClass = '';
  1364. switch ($linktype) {
  1365. case 'edit':
  1366. $linkClass = 'edit_user_anchor';
  1367. break;
  1368. case 'export':
  1369. $linkClass = 'export_user_anchor ajax';
  1370. break;
  1371. }
  1372. $params = [
  1373. 'username' => $username,
  1374. 'hostname' => $hostname,
  1375. ];
  1376. switch ($linktype) {
  1377. case 'edit':
  1378. $params['dbname'] = $dbname;
  1379. $params['tablename'] = $tablename;
  1380. $params['routinename'] = $routinename;
  1381. break;
  1382. case 'revoke':
  1383. $params['dbname'] = $dbname;
  1384. $params['tablename'] = $tablename;
  1385. $params['routinename'] = $routinename;
  1386. $params['revokeall'] = 1;
  1387. break;
  1388. case 'export':
  1389. $params['initial'] = $initial;
  1390. $params['export'] = 1;
  1391. break;
  1392. }
  1393. $action = [];
  1394. switch ($linktype) {
  1395. case 'edit':
  1396. $action['icon'] = 'b_usredit';
  1397. $action['text'] = __('Edit privileges');
  1398. break;
  1399. case 'revoke':
  1400. $action['icon'] = 'b_usrdrop';
  1401. $action['text'] = __('Revoke');
  1402. break;
  1403. case 'export':
  1404. $action['icon'] = 'b_tblexport';
  1405. $action['text'] = __('Export');
  1406. break;
  1407. }
  1408. return $this->template->render('server/privileges/get_user_link', [
  1409. 'link_class' => $linkClass,
  1410. 'is_revoke' => $linktype === 'revoke',
  1411. 'url_params' => $params,
  1412. 'action' => $action,
  1413. ]);
  1414. }
  1415. /**
  1416. * Returns number of defined user groups
  1417. */
  1418. public function getUserGroupCount(): int
  1419. {
  1420. $cfgRelation = $this->relation->getRelationsParam();
  1421. $userGroupTable = Util::backquote($cfgRelation['db'])
  1422. . '.' . Util::backquote($cfgRelation['usergroups']);
  1423. $sqlQuery = 'SELECT COUNT(*) FROM ' . $userGroupTable;
  1424. return (int) $this->dbi->fetchValue($sqlQuery, 0, 0, DatabaseInterface::CONNECT_CONTROL);
  1425. }
  1426. /**
  1427. * Returns name of user group that user is part of
  1428. *
  1429. * @param string $username User name
  1430. *
  1431. * @return mixed|null usergroup if found or null if not found
  1432. */
  1433. public function getUserGroupForUser($username)
  1434. {
  1435. $cfgRelation = $this->relation->getRelationsParam();
  1436. if (empty($cfgRelation['db']) || empty($cfgRelation['users'])) {
  1437. return null;
  1438. }
  1439. $userTable = Util::backquote($cfgRelation['db'])
  1440. . '.' . Util::backquote($cfgRelation['users']);
  1441. $sqlQuery = 'SELECT `usergroup` FROM ' . $userTable
  1442. . ' WHERE `username` = \'' . $username . '\''
  1443. . ' LIMIT 1';
  1444. $usergroup = $this->dbi->fetchValue($sqlQuery, 0, 0, DatabaseInterface::CONNECT_CONTROL);
  1445. if ($usergroup === false) {
  1446. return null;
  1447. }
  1448. return $usergroup;
  1449. }
  1450. /**
  1451. * This function return the extra data array for the ajax behavior
  1452. *
  1453. * @param string $password password
  1454. * @param string $sqlQuery sql query
  1455. * @param string $hostname hostname
  1456. * @param string $username username
  1457. *
  1458. * @return array
  1459. */
  1460. public function getExtraDataForAjaxBehavior(
  1461. $password,
  1462. $sqlQuery,
  1463. $hostname,
  1464. $username
  1465. ) {
  1466. if (isset($GLOBALS['dbname'])) {
  1467. //if (preg_match('/\\\\(?:_|%)/i', $dbname)) {
  1468. if (preg_match('/(?<!\\\\)(?:_|%)/', $GLOBALS['dbname'])) {
  1469. $dbnameIsWildcard = true;
  1470. } else {
  1471. $dbnameIsWildcard = false;
  1472. }
  1473. }
  1474. $userGroupCount = 0;
  1475. if ($GLOBALS['cfgRelation']['menuswork']) {
  1476. $userGroupCount = $this->getUserGroupCount();
  1477. }
  1478. $extraData = [];
  1479. if (strlen($sqlQuery) > 0) {
  1480. $extraData['sql_query'] = Generator::getMessage('', $sqlQuery);
  1481. }
  1482. if (isset($_POST['change_copy'])) {
  1483. $cfgRelation = $this->relation->getRelationsParam();
  1484. $user = [
  1485. 'name' => $username,
  1486. 'host' => $hostname,
  1487. 'has_password' => ! empty($password) || isset($_POST['pma_pw']),
  1488. 'privileges' => implode(', ', $this->extractPrivInfo(null, true)),
  1489. 'has_group' => ! empty($cfgRelation['users']) && ! empty($cfgRelation['usergroups']),
  1490. 'has_group_edit' => $cfgRelation['menuswork'] && $userGroupCount > 0,
  1491. 'has_grant' => isset($_POST['Grant_priv']) && $_POST['Grant_priv'] === 'Y',
  1492. ];
  1493. $extraData['new_user_string'] = $this->template->render('server/privileges/new_user_ajax', [
  1494. 'user' => $user,
  1495. 'is_grantuser' => $this->dbi->isGrantUser(),
  1496. 'initial' => $_GET['initial'] ?? '',
  1497. ]);
  1498. /**
  1499. * Generate the string for this alphabet's initial, to update the user
  1500. * pagination
  1501. */
  1502. $newUserInitial = mb_strtoupper(
  1503. mb_substr($username, 0, 1)
  1504. );
  1505. $newUserInitialString = '<a href="';
  1506. $newUserInitialString .= Url::getFromRoute('/server/privileges', ['initial' => $newUserInitial]);
  1507. $newUserInitialString .= '">' . $newUserInitial . '</a>';
  1508. $extraData['new_user_initial'] = $newUserInitial;
  1509. $extraData['new_user_initial_string'] = $newUserInitialString;
  1510. }
  1511. if (isset($_POST['update_privs'])) {
  1512. $extraData['db_specific_privs'] = false;
  1513. $extraData['db_wildcard_privs'] = false;
  1514. if (isset($dbnameIsWildcard)) {
  1515. $extraData['db_specific_privs'] = ! $dbnameIsWildcard;
  1516. $extraData['db_wildcard_privs'] = $dbnameIsWildcard;
  1517. }
  1518. $newPrivileges = implode(', ', $this->extractPrivInfo(null, true));
  1519. $extraData['new_privileges'] = $newPrivileges;
  1520. }
  1521. if (isset($_GET['validate_username'])) {
  1522. $sqlQuery = "SELECT * FROM `mysql`.`user` WHERE `User` = '"
  1523. . $this->dbi->escapeString($_GET['username']) . "';";
  1524. $res = $this->dbi->query($sqlQuery);
  1525. $row = $this->dbi->fetchRow($res);
  1526. if (empty($row)) {
  1527. $extraData['user_exists'] = false;
  1528. } else {
  1529. $extraData['user_exists'] = true;
  1530. }
  1531. }
  1532. return $extraData;
  1533. }
  1534. /**
  1535. * no db name given, so we want all privs for the given user
  1536. * db name was given, so we want all user specific rights for this db
  1537. * So this function returns user rights as an array
  1538. *
  1539. * @param string $username username
  1540. * @param string $hostname host name
  1541. * @param string $type database or table
  1542. * @param string $dbname database name
  1543. *
  1544. * @return array database rights
  1545. */
  1546. public function getUserSpecificRights($username, $hostname, $type, $dbname = '')
  1547. {
  1548. $userHostCondition = ' WHERE `User`'
  1549. . " = '" . $this->dbi->escapeString($username) . "'"
  1550. . ' AND `Host`'
  1551. . " = '" . $this->dbi->escapeString($hostname) . "'";
  1552. if ($type === 'database') {
  1553. $tablesToSearchForUsers = [
  1554. 'tables_priv',
  1555. 'columns_priv',
  1556. 'procs_priv',
  1557. ];
  1558. $dbOrTableName = 'Db';
  1559. } elseif ($type === 'table') {
  1560. $userHostCondition .= " AND `Db` LIKE '"
  1561. . $this->dbi->escapeString($dbname) . "'";
  1562. $tablesToSearchForUsers = ['columns_priv'];
  1563. $dbOrTableName = 'Table_name';
  1564. } else { // routine
  1565. $userHostCondition .= " AND `Db` LIKE '"
  1566. . $this->dbi->escapeString($dbname) . "'";
  1567. $tablesToSearchForUsers = ['procs_priv'];
  1568. $dbOrTableName = 'Routine_name';
  1569. }
  1570. // we also want privileges for this user not in table `db` but in other table
  1571. $tables = $this->dbi->fetchResult('SHOW TABLES FROM `mysql`;');
  1572. $dbRightsSqls = [];
  1573. foreach ($tablesToSearchForUsers as $tableSearchIn) {
  1574. if (! in_array($tableSearchIn, $tables)) {
  1575. continue;
  1576. }
  1577. $dbRightsSqls[] = '
  1578. SELECT DISTINCT `' . $dbOrTableName . '`
  1579. FROM `mysql`.' . Util::backquote($tableSearchIn)
  1580. . $userHostCondition;
  1581. }
  1582. $userDefaults = [
  1583. $dbOrTableName => '',
  1584. 'Grant_priv' => 'N',
  1585. 'privs' => ['USAGE'],
  1586. 'Column_priv' => true,
  1587. ];
  1588. // for the rights
  1589. $dbRights = [];
  1590. $dbRightsSql = '(' . implode(') UNION (', $dbRightsSqls) . ')'
  1591. . ' ORDER BY `' . $dbOrTableName . '` ASC';
  1592. $dbRightsResult = $this->dbi->query($dbRightsSql);
  1593. while ($dbRightsRow = $this->dbi->fetchAssoc($dbRightsResult)) {
  1594. $dbRightsRow = array_merge($userDefaults, $dbRightsRow);
  1595. if ($type === 'database') {
  1596. // only Db names in the table `mysql`.`db` uses wildcards
  1597. // as we are in the db specific rights display we want
  1598. // all db names escaped, also from other sources
  1599. $dbRightsRow['Db'] = Util::escapeMysqlWildcards($dbRightsRow['Db']);
  1600. }
  1601. $dbRights[$dbRightsRow[$dbOrTableName]] = $dbRightsRow;
  1602. }
  1603. $this->dbi->freeResult($dbRightsResult);
  1604. if ($type === 'database') {
  1605. $sqlQuery = 'SELECT * FROM `mysql`.`db`'
  1606. . $userHostCondition . ' ORDER BY `Db` ASC';
  1607. } elseif ($type === 'table') {
  1608. $sqlQuery = 'SELECT `Table_name`,'
  1609. . ' `Table_priv`,'
  1610. . ' IF(`Column_priv` = _latin1 \'\', 0, 1)'
  1611. . ' AS \'Column_priv\''
  1612. . ' FROM `mysql`.`tables_priv`'
  1613. . $userHostCondition
  1614. . ' ORDER BY `Table_name` ASC;';
  1615. } else {
  1616. $sqlQuery = 'SELECT `Routine_name`, `Proc_priv`'
  1617. . ' FROM `mysql`.`procs_priv`'
  1618. . $userHostCondition
  1619. . ' ORDER BY `Routine_name`';
  1620. }
  1621. $result = $this->dbi->query($sqlQuery);
  1622. while ($row = $this->dbi->fetchAssoc($result)) {
  1623. if (isset($dbRights[$row[$dbOrTableName]])) {
  1624. $dbRights[$row[$dbOrTableName]] = array_merge($dbRights[$row[$dbOrTableName]], $row);
  1625. } else {
  1626. $dbRights[$row[$dbOrTableName]] = $row;
  1627. }
  1628. if ($type !== 'database') {
  1629. continue;
  1630. }
  1631. // there are db specific rights for this user
  1632. // so we can drop this db rights
  1633. $dbRights[$row['Db']]['can_delete'] = true;
  1634. }
  1635. $this->dbi->freeResult($result);
  1636. return $dbRights;
  1637. }
  1638. /**
  1639. * Parses Proc_priv data
  1640. *
  1641. * @param string $privs Proc_priv
  1642. *
  1643. * @return array
  1644. */
  1645. public function parseProcPriv($privs)
  1646. {
  1647. $result = [
  1648. 'Alter_routine_priv' => 'N',
  1649. 'Execute_priv' => 'N',
  1650. 'Grant_priv' => 'N',
  1651. ];
  1652. foreach (explode(',', (string) $privs) as $priv) {
  1653. if ($priv === 'Alter Routine') {
  1654. $result['Alter_routine_priv'] = 'Y';
  1655. } else {
  1656. $result[$priv . '_priv'] = 'Y';
  1657. }
  1658. }
  1659. return $result;
  1660. }
  1661. /**
  1662. * Get a HTML table for display user's table specific or database specific rights
  1663. *
  1664. * @param string $username username
  1665. * @param string $hostname host name
  1666. * @param string $type database, table or routine
  1667. * @param string $dbname database name
  1668. *
  1669. * @return string
  1670. */
  1671. public function getHtmlForAllTableSpecificRights(
  1672. $username,
  1673. $hostname,
  1674. $type,
  1675. $dbname = ''
  1676. ) {
  1677. $uiData = [
  1678. 'database' => [
  1679. 'form_id' => 'database_specific_priv',
  1680. 'sub_menu_label' => __('Database'),
  1681. 'legend' => __('Database-specific privileges'),
  1682. 'type_label' => __('Database'),
  1683. ],
  1684. 'table' => [
  1685. 'form_id' => 'table_specific_priv',
  1686. 'sub_menu_label' => __('Table'),
  1687. 'legend' => __('Table-specific privileges'),
  1688. 'type_label' => __('Table'),
  1689. ],
  1690. 'routine' => [
  1691. 'form_id' => 'routine_specific_priv',
  1692. 'sub_menu_label' => __('Routine'),
  1693. 'legend' => __('Routine-specific privileges'),
  1694. 'type_label' => __('Routine'),
  1695. ],
  1696. ];
  1697. /**
  1698. * no db name given, so we want all privs for the given user
  1699. * db name was given, so we want all user specific rights for this db
  1700. */
  1701. $dbRights = $this->getUserSpecificRights($username, $hostname, $type, $dbname);
  1702. ksort($dbRights);
  1703. $foundRows = [];
  1704. $privileges = [];
  1705. foreach ($dbRights as $row) {
  1706. $onePrivilege = [];
  1707. $paramTableName = '';
  1708. $paramRoutineName = '';
  1709. if ($type === 'database') {
  1710. $name = $row['Db'];
  1711. $onePrivilege['grant'] = $row['Grant_priv'] === 'Y';
  1712. $onePrivilege['table_privs'] = ! empty($row['Table_priv'])
  1713. || ! empty($row['Column_priv']);
  1714. $onePrivilege['privileges'] = implode(',', $this->extractPrivInfo($row, true));
  1715. $paramDbName = $row['Db'];
  1716. } elseif ($type === 'table') {
  1717. $name = $row['Table_name'];
  1718. $onePrivilege['grant'] = in_array(
  1719. 'Grant',
  1720. explode(',', $row['Table_priv'])
  1721. );
  1722. $onePrivilege['column_privs'] = ! empty($row['Column_priv']);
  1723. $onePrivilege['privileges'] = implode(',', $this->extractPrivInfo($row, true));
  1724. $paramDbName = Util::escapeMysqlWildcards($dbname);
  1725. $paramTableName = $row['Table_name'];
  1726. } else { // routine
  1727. $name = $row['Routine_name'];
  1728. $onePrivilege['grant'] = in_array(
  1729. 'Grant',
  1730. explode(',', $row['Proc_priv'])
  1731. );
  1732. $privs = $this->parseProcPriv($row['Proc_priv']);
  1733. $onePrivilege['privileges'] = implode(
  1734. ',',
  1735. $this->extractPrivInfo($privs, true)
  1736. );
  1737. $paramDbName = Util::escapeMysqlWildcards($dbname);
  1738. $paramRoutineName = $row['Routine_name'];
  1739. }
  1740. $foundRows[] = $name;
  1741. $onePrivilege['name'] = $name;
  1742. $onePrivilege['edit_link'] = '';
  1743. if ($this->dbi->isGrantUser()) {
  1744. $onePrivilege['edit_link'] = $this->getUserLink(
  1745. 'edit',
  1746. $username,
  1747. $hostname,
  1748. $paramDbName,
  1749. $paramTableName,
  1750. $paramRoutineName
  1751. );
  1752. }
  1753. $onePrivilege['revoke_link'] = '';
  1754. if ($type !== 'database' || ! empty($row['can_delete'])) {
  1755. $onePrivilege['revoke_link'] = $this->getUserLink(
  1756. 'revoke',
  1757. $username,
  1758. $hostname,
  1759. $paramDbName,
  1760. $paramTableName,
  1761. $paramRoutineName
  1762. );
  1763. }
  1764. $privileges[] = $onePrivilege;
  1765. }
  1766. $data = $uiData[$type];
  1767. $data['privileges'] = $privileges;
  1768. $data['username'] = $username;
  1769. $data['hostname'] = $hostname;
  1770. $data['database'] = $dbname;
  1771. $data['type'] = $type;
  1772. if ($type === 'database') {
  1773. $predDbArray = $GLOBALS['dblist']->databases;
  1774. $databasesToSkip = [
  1775. 'information_schema',
  1776. 'performance_schema',
  1777. ];
  1778. $databases = [];
  1779. $escapedDatabases = [];
  1780. if (! empty($predDbArray)) {
  1781. foreach ($predDbArray as $currentDb) {
  1782. if (in_array($currentDb, $databasesToSkip)) {
  1783. continue;
  1784. }
  1785. $currentDbEscaped = Util::escapeMysqlWildcards($currentDb);
  1786. // cannot use array_diff() once, outside of the loop,
  1787. // because the list of databases has special characters
  1788. // already escaped in $foundRows,
  1789. // contrary to the output of SHOW DATABASES
  1790. if (in_array($currentDbEscaped, $foundRows)) {
  1791. continue;
  1792. }
  1793. $databases[] = $currentDb;
  1794. $escapedDatabases[] = $currentDbEscaped;
  1795. }
  1796. }
  1797. $data['databases'] = $databases;
  1798. $data['escaped_databases'] = $escapedDatabases;
  1799. } elseif ($type === 'table') {
  1800. $result = @$this->dbi->tryQuery(
  1801. 'SHOW TABLES FROM ' . Util::backquote($dbname),
  1802. DatabaseInterface::CONNECT_USER,
  1803. DatabaseInterface::QUERY_STORE
  1804. );
  1805. $tables = [];
  1806. if ($result) {
  1807. while ($row = $this->dbi->fetchRow($result)) {
  1808. if (in_array($row[0], $foundRows)) {
  1809. continue;
  1810. }
  1811. $tables[] = $row[0];
  1812. }
  1813. $this->dbi->freeResult($result);
  1814. }
  1815. $data['tables'] = $tables;
  1816. } else { // routine
  1817. $routineData = $this->dbi->getRoutines($dbname);
  1818. $routines = [];
  1819. foreach ($routineData as $routine) {
  1820. if (in_array($routine['name'], $foundRows)) {
  1821. continue;
  1822. }
  1823. $routines[] = $routine['name'];
  1824. }
  1825. $data['routines'] = $routines;
  1826. }
  1827. return $this->template->render('server/privileges/privileges_summary', $data);
  1828. }
  1829. /**
  1830. * Get HTML for display the users overview
  1831. * (if less than 50 users, display them immediately)
  1832. *
  1833. * @param array $result ran sql query
  1834. * @param array $dbRights user's database rights array
  1835. * @param string $textDir text directory
  1836. *
  1837. * @return string HTML snippet
  1838. */
  1839. public function getUsersOverview($result, array $dbRights, $textDir)
  1840. {
  1841. $cfgRelation = $this->relation->getRelationsParam();
  1842. while ($row = $this->dbi->fetchAssoc($result)) {
  1843. $row['privs'] = $this->extractPrivInfo($row, true);
  1844. $dbRights[$row['User']][$row['Host']] = $row;
  1845. }
  1846. $this->dbi->freeResult($result);
  1847. $userGroupCount = 0;
  1848. if ($cfgRelation['menuswork']) {
  1849. $sqlQuery = 'SELECT * FROM ' . Util::backquote($cfgRelation['db'])
  1850. . '.' . Util::backquote($cfgRelation['users']);
  1851. $result = $this->relation->queryAsControlUser($sqlQuery, false);
  1852. $groupAssignment = [];
  1853. if ($result) {
  1854. while ($row = $this->dbi->fetchAssoc($result)) {
  1855. $groupAssignment[$row['username']] = $row['usergroup'];
  1856. }
  1857. }
  1858. $this->dbi->freeResult($result);
  1859. $userGroupCount = $this->getUserGroupCount();
  1860. }
  1861. $hosts = [];
  1862. $hasAccountLocking = Compatibility::hasAccountLocking($this->dbi->isMariaDB(), $this->dbi->getVersion());
  1863. foreach ($dbRights as $user) {
  1864. ksort($user);
  1865. foreach ($user as $host) {
  1866. $res = $this->getUserPrivileges((string) $host['User'], (string) $host['Host'], $hasAccountLocking);
  1867. $hasPassword = false;
  1868. if (
  1869. (isset($res['authentication_string'])
  1870. && ! empty($res['authentication_string']))
  1871. || (isset($res['Password'])
  1872. && ! empty($res['Password']))
  1873. ) {
  1874. $hasPassword = true;
  1875. }
  1876. $hosts[] = [
  1877. 'user' => $host['User'],
  1878. 'host' => $host['Host'],
  1879. 'has_password' => $hasPassword,
  1880. 'has_select_priv' => isset($host['Select_priv']),
  1881. 'privileges' => $host['privs'],
  1882. 'group' => $groupAssignment[$host['User']] ?? '',
  1883. 'has_grant' => $host['Grant_priv'] === 'Y',
  1884. 'is_account_locked' => isset($res['account_locked']) && $res['account_locked'] === 'Y',
  1885. ];
  1886. }
  1887. }
  1888. return $this->template->render('server/privileges/users_overview', [
  1889. 'menus_work' => $cfgRelation['menuswork'],
  1890. 'user_group_count' => $userGroupCount,
  1891. 'text_dir' => $textDir,
  1892. 'initial' => $_GET['initial'] ?? '',
  1893. 'hosts' => $hosts,
  1894. 'is_grantuser' => $this->dbi->isGrantUser(),
  1895. 'is_createuser' => $this->dbi->isCreateUser(),
  1896. 'has_account_locking' => $hasAccountLocking,
  1897. ]);
  1898. }
  1899. /**
  1900. * Get HTML for Displays the initials
  1901. *
  1902. * @param array $arrayInitials array for all initials, even non A-Z
  1903. *
  1904. * @return string HTML snippet
  1905. */
  1906. public function getHtmlForInitials(array $arrayInitials)
  1907. {
  1908. // initialize to false the letters A-Z
  1909. for ($letterCounter = 1; $letterCounter < 27; $letterCounter++) {
  1910. if (isset($arrayInitials[mb_chr($letterCounter + 64)])) {
  1911. continue;
  1912. }
  1913. $arrayInitials[mb_chr($letterCounter + 64)] = false;
  1914. }
  1915. $initials = $this->dbi->tryQuery(
  1916. 'SELECT DISTINCT UPPER(LEFT(`User`,1)) FROM `user` ORDER BY UPPER(LEFT(`User`,1)) ASC',
  1917. DatabaseInterface::CONNECT_USER,
  1918. DatabaseInterface::QUERY_STORE
  1919. );
  1920. if ($initials) {
  1921. while ([$tmpInitial] = $this->dbi->fetchRow($initials)) {
  1922. $arrayInitials[$tmpInitial] = true;
  1923. }
  1924. }
  1925. // Display the initials, which can be any characters, not
  1926. // just letters. For letters A-Z, we add the non-used letters
  1927. // as greyed out.
  1928. uksort($arrayInitials, 'strnatcasecmp');
  1929. return $this->template->render('server/privileges/initials_row', [
  1930. 'array_initials' => $arrayInitials,
  1931. 'initial' => $_GET['initial'] ?? null,
  1932. 'viewing_mode' => $_GET['viewing_mode'] ?? null,
  1933. ]);
  1934. }
  1935. /**
  1936. * Get the database rights array for Display user overview
  1937. *
  1938. * @return array database rights array
  1939. */
  1940. public function getDbRightsForUserOverview()
  1941. {
  1942. // we also want users not in table `user` but in other table
  1943. $tables = $this->dbi->fetchResult('SHOW TABLES FROM `mysql`;');
  1944. $tablesSearchForUsers = [
  1945. 'user',
  1946. 'db',
  1947. 'tables_priv',
  1948. 'columns_priv',
  1949. 'procs_priv',
  1950. ];
  1951. $dbRightsSqls = [];
  1952. foreach ($tablesSearchForUsers as $tableSearchIn) {
  1953. if (! in_array($tableSearchIn, $tables)) {
  1954. continue;
  1955. }
  1956. $dbRightsSqls[] = 'SELECT DISTINCT `User`, `Host` FROM `mysql`.`'
  1957. . $tableSearchIn . '` '
  1958. . (isset($_GET['initial'])
  1959. ? $this->rangeOfUsers($_GET['initial'])
  1960. : '');
  1961. }
  1962. $userDefaults = [
  1963. 'User' => '',
  1964. 'Host' => '%',
  1965. 'Password' => '?',
  1966. 'Grant_priv' => 'N',
  1967. 'privs' => ['USAGE'],
  1968. ];
  1969. // for the rights
  1970. $dbRights = [];
  1971. $dbRightsSql = '(' . implode(') UNION (', $dbRightsSqls) . ')'
  1972. . ' ORDER BY `User` ASC, `Host` ASC';
  1973. $dbRightsResult = $this->dbi->query($dbRightsSql);
  1974. while ($dbRightsRow = $this->dbi->fetchAssoc($dbRightsResult)) {
  1975. $dbRightsRow = array_merge($userDefaults, $dbRightsRow);
  1976. $dbRights[$dbRightsRow['User']][$dbRightsRow['Host']] = $dbRightsRow;
  1977. }
  1978. $this->dbi->freeResult($dbRightsResult);
  1979. ksort($dbRights);
  1980. return $dbRights;
  1981. }
  1982. /**
  1983. * Delete user and get message and sql query for delete user in privileges
  1984. *
  1985. * @param array $queries queries
  1986. *
  1987. * @return array Message
  1988. */
  1989. public function deleteUser(array $queries)
  1990. {
  1991. $sqlQuery = '';
  1992. if (empty($queries)) {
  1993. $message = Message::error(__('No users selected for deleting!'));
  1994. } else {
  1995. if ($_POST['mode'] == 3) {
  1996. $queries[] = '# ' . __('Reloading the privileges') . ' …';
  1997. $queries[] = 'FLUSH PRIVILEGES;';
  1998. }
  1999. $dropUserError = '';
  2000. foreach ($queries as $sqlQuery) {
  2001. if ($sqlQuery[0] === '#') {
  2002. continue;
  2003. }
  2004. if ($this->dbi->tryQuery($sqlQuery)) {
  2005. continue;
  2006. }
  2007. $dropUserError .= $this->dbi->getError() . "\n";
  2008. }
  2009. // tracking sets this, causing the deleted db to be shown in navi
  2010. unset($GLOBALS['db']);
  2011. $sqlQuery = implode("\n", $queries);
  2012. if (! empty($dropUserError)) {
  2013. $message = Message::rawError($dropUserError);
  2014. } else {
  2015. $message = Message::success(
  2016. __('The selected users have been deleted successfully.')
  2017. );
  2018. }
  2019. }
  2020. return [
  2021. $sqlQuery,
  2022. $message,
  2023. ];
  2024. }
  2025. /**
  2026. * Update the privileges and return the success or error message
  2027. *
  2028. * @return array success message or error message for update
  2029. */
  2030. public function updatePrivileges(
  2031. string $username,
  2032. string $hostname,
  2033. string $tablename,
  2034. string $dbname,
  2035. string $itemType
  2036. ): array {
  2037. $dbAndTable = $this->wildcardEscapeForGrant($dbname, $tablename);
  2038. $sqlQuery0 = 'REVOKE ALL PRIVILEGES ON ' . $itemType . ' ' . $dbAndTable
  2039. . ' FROM \'' . $this->dbi->escapeString($username)
  2040. . '\'@\'' . $this->dbi->escapeString($hostname) . '\';';
  2041. if (! isset($_POST['Grant_priv']) || $_POST['Grant_priv'] !== 'Y') {
  2042. $sqlQuery1 = 'REVOKE GRANT OPTION ON ' . $itemType . ' ' . $dbAndTable
  2043. . ' FROM \'' . $this->dbi->escapeString($username) . '\'@\''
  2044. . $this->dbi->escapeString($hostname) . '\';';
  2045. } else {
  2046. $sqlQuery1 = '';
  2047. }
  2048. $grantBackQuery = null;
  2049. $alterUserQuery = null;
  2050. // Should not do a GRANT USAGE for a table-specific privilege, it
  2051. // causes problems later (cannot revoke it)
  2052. if (! (strlen($tablename) > 0 && implode('', $this->extractPrivInfo()) === 'USAGE')) {
  2053. [$grantBackQuery, $alterUserQuery] = $this->generateQueriesForUpdatePrivileges(
  2054. $itemType,
  2055. $dbAndTable,
  2056. $username,
  2057. $hostname,
  2058. $dbname
  2059. );
  2060. }
  2061. if (! $this->dbi->tryQuery($sqlQuery0)) {
  2062. // This might fail when the executing user does not have
  2063. // ALL PRIVILEGES themselves.
  2064. // See https://github.com/phpmyadmin/phpmyadmin/issues/9673
  2065. $sqlQuery0 = '';
  2066. }
  2067. if (! empty($sqlQuery1) && ! $this->dbi->tryQuery($sqlQuery1)) {
  2068. // this one may fail, too...
  2069. $sqlQuery1 = '';
  2070. }
  2071. if ($grantBackQuery !== null) {
  2072. $this->dbi->query($grantBackQuery);
  2073. } else {
  2074. $grantBackQuery = '';
  2075. }
  2076. if ($alterUserQuery !== null) {
  2077. $this->dbi->query($alterUserQuery);
  2078. } else {
  2079. $alterUserQuery = '';
  2080. }
  2081. $sqlQuery = $sqlQuery0 . ' ' . $sqlQuery1 . ' ' . $grantBackQuery . ' ' . $alterUserQuery;
  2082. $message = Message::success(__('You have updated the privileges for %s.'));
  2083. $message->addParam('\'' . $username . '\'@\'' . $hostname . '\'');
  2084. return [
  2085. $sqlQuery,
  2086. $message,
  2087. ];
  2088. }
  2089. /**
  2090. * Generate the query for the GRANTS and requirements + limits
  2091. *
  2092. * @return array<int,string|null>
  2093. */
  2094. private function generateQueriesForUpdatePrivileges(
  2095. string $itemType,
  2096. string $dbAndTable,
  2097. string $username,
  2098. string $hostname,
  2099. string $dbname
  2100. ): array {
  2101. $alterUserQuery = null;
  2102. $grantBackQuery = 'GRANT ' . implode(', ', $this->extractPrivInfo())
  2103. . ' ON ' . $itemType . ' ' . $dbAndTable
  2104. . ' TO \'' . $this->dbi->escapeString($username) . '\'@\''
  2105. . $this->dbi->escapeString($hostname) . '\'';
  2106. $isMySqlOrPercona = Compatibility::isMySqlOrPerconaDb();
  2107. $needsToUseAlter = $isMySqlOrPercona && $this->dbi->getVersion() >= 80011;
  2108. if ($needsToUseAlter) {
  2109. $alterUserQuery = 'ALTER USER \'' . $this->dbi->escapeString($username) . '\'@\''
  2110. . $this->dbi->escapeString($hostname) . '\' ';
  2111. }
  2112. if (strlen($dbname) === 0) {
  2113. // add REQUIRE clause
  2114. if ($needsToUseAlter) {
  2115. $alterUserQuery .= $this->getRequireClause();
  2116. } else {
  2117. $grantBackQuery .= $this->getRequireClause();
  2118. }
  2119. }
  2120. if (
  2121. (isset($_POST['Grant_priv']) && $_POST['Grant_priv'] === 'Y')
  2122. || (strlen($dbname) === 0
  2123. && (isset($_POST['max_questions']) || isset($_POST['max_connections'])
  2124. || isset($_POST['max_updates'])
  2125. || isset($_POST['max_user_connections'])))
  2126. ) {
  2127. if ($needsToUseAlter) {
  2128. $alterUserQuery .= $this->getWithClauseForAddUserAndUpdatePrivs();
  2129. } else {
  2130. $grantBackQuery .= $this->getWithClauseForAddUserAndUpdatePrivs();
  2131. }
  2132. }
  2133. $grantBackQuery .= ';';
  2134. if ($needsToUseAlter) {
  2135. $alterUserQuery .= ';';
  2136. }
  2137. return [$grantBackQuery, $alterUserQuery];
  2138. }
  2139. /**
  2140. * Get List of information: Changes / copies a user
  2141. *
  2142. * @return array
  2143. */
  2144. public function getDataForChangeOrCopyUser()
  2145. {
  2146. $queries = null;
  2147. $password = null;
  2148. if (isset($_POST['change_copy'])) {
  2149. $userHostCondition = ' WHERE `User` = '
  2150. . "'" . $this->dbi->escapeString($_POST['old_username']) . "'"
  2151. . ' AND `Host` = '
  2152. . "'" . $this->dbi->escapeString($_POST['old_hostname']) . "';";
  2153. $row = $this->dbi->fetchSingleRow('SELECT * FROM `mysql`.`user` ' . $userHostCondition);
  2154. if (! $row) {
  2155. $response = ResponseRenderer::getInstance();
  2156. $response->addHTML(
  2157. Message::notice(__('No user found.'))->getDisplay()
  2158. );
  2159. unset($_POST['change_copy']);
  2160. } else {
  2161. foreach ($row as $key => $value) {
  2162. $GLOBALS[$key] = $value;
  2163. }
  2164. $serverVersion = $this->dbi->getVersion();
  2165. // Recent MySQL versions have the field "Password" in mysql.user,
  2166. // so the previous extract creates $row['Password'] but this script
  2167. // uses $password
  2168. if (! isset($row['password']) && isset($row['Password'])) {
  2169. $row['password'] = $row['Password'];
  2170. }
  2171. if (
  2172. Compatibility::isMySqlOrPerconaDb()
  2173. && $serverVersion >= 50606
  2174. && $serverVersion < 50706
  2175. && ((isset($row['authentication_string'])
  2176. && empty($row['password']))
  2177. || (isset($row['plugin'])
  2178. && $row['plugin'] === 'sha256_password'))
  2179. ) {
  2180. $row['password'] = $row['authentication_string'];
  2181. }
  2182. if (
  2183. Compatibility::isMariaDb()
  2184. && $serverVersion >= 50500
  2185. && isset($row['authentication_string'])
  2186. && empty($row['password'])
  2187. ) {
  2188. $row['password'] = $row['authentication_string'];
  2189. }
  2190. // Always use 'authentication_string' column
  2191. // for MySQL 5.7.6+ since it does not have
  2192. // the 'password' column at all
  2193. if (
  2194. Compatibility::isMySqlOrPerconaDb()
  2195. && $serverVersion >= 50706
  2196. && isset($row['authentication_string'])
  2197. ) {
  2198. $row['password'] = $row['authentication_string'];
  2199. }
  2200. $password = $row['password'];
  2201. $queries = [];
  2202. }
  2203. }
  2204. return [
  2205. $queries,
  2206. $password,
  2207. ];
  2208. }
  2209. /**
  2210. * Update Data for information: Deletes users
  2211. *
  2212. * @param array $queries queries array
  2213. *
  2214. * @return array
  2215. */
  2216. public function getDataForDeleteUsers($queries)
  2217. {
  2218. if (isset($_POST['change_copy'])) {
  2219. $selectedUsr = [
  2220. $_POST['old_username'] . '&amp;#27;' . $_POST['old_hostname'],
  2221. ];
  2222. } else {
  2223. // null happens when no user was selected
  2224. $selectedUsr = $_POST['selected_usr'] ?? null;
  2225. $queries = [];
  2226. }
  2227. // this happens, was seen in https://reports.phpmyadmin.net/reports/view/17146
  2228. if (! is_array($selectedUsr)) {
  2229. return [];
  2230. }
  2231. foreach ($selectedUsr as $eachUser) {
  2232. [$thisUser, $thisHost] = explode('&amp;#27;', $eachUser);
  2233. $queries[] = '# '
  2234. . sprintf(
  2235. __('Deleting %s'),
  2236. '\'' . $thisUser . '\'@\'' . $thisHost . '\''
  2237. )
  2238. . ' ...';
  2239. $queries[] = 'DROP USER \''
  2240. . $this->dbi->escapeString($thisUser)
  2241. . '\'@\'' . $this->dbi->escapeString($thisHost) . '\';';
  2242. $this->relationCleanup->user($thisUser);
  2243. if (! isset($_POST['drop_users_db'])) {
  2244. continue;
  2245. }
  2246. $queries[] = 'DROP DATABASE IF EXISTS '
  2247. . Util::backquote($thisUser) . ';';
  2248. $GLOBALS['reload'] = true;
  2249. }
  2250. return $queries;
  2251. }
  2252. /**
  2253. * update Message For Reload
  2254. */
  2255. public function updateMessageForReload(): ?Message
  2256. {
  2257. $message = null;
  2258. if (isset($_GET['flush_privileges'])) {
  2259. $sqlQuery = 'FLUSH PRIVILEGES;';
  2260. $this->dbi->query($sqlQuery);
  2261. $message = Message::success(
  2262. __('The privileges were reloaded successfully.')
  2263. );
  2264. }
  2265. if (isset($_GET['validate_username'])) {
  2266. $message = Message::success();
  2267. }
  2268. return $message;
  2269. }
  2270. /**
  2271. * update Data For Queries from queries_for_display
  2272. *
  2273. * @param array $queries queries array
  2274. * @param array|null $queriesForDisplay queries array for display
  2275. *
  2276. * @return array
  2277. */
  2278. public function getDataForQueries(array $queries, $queriesForDisplay)
  2279. {
  2280. $tmpCount = 0;
  2281. foreach ($queries as $sqlQuery) {
  2282. if ($sqlQuery[0] !== '#') {
  2283. $this->dbi->query($sqlQuery);
  2284. }
  2285. // when there is a query containing a hidden password, take it
  2286. // instead of the real query sent
  2287. if (isset($queriesForDisplay[$tmpCount])) {
  2288. $queries[$tmpCount] = $queriesForDisplay[$tmpCount];
  2289. }
  2290. $tmpCount++;
  2291. }
  2292. return $queries;
  2293. }
  2294. /**
  2295. * update Data for information: Adds a user
  2296. *
  2297. * @param string|array|null $dbname db name
  2298. * @param string $username user name
  2299. * @param string $hostname host name
  2300. * @param string|null $password password
  2301. * @param bool $isMenuwork is_menuwork set?
  2302. *
  2303. * @return array
  2304. */
  2305. public function addUser(
  2306. $dbname,
  2307. $username,
  2308. $hostname,
  2309. ?string $password,
  2310. $isMenuwork
  2311. ) {
  2312. $message = null;
  2313. $queries = null;
  2314. $queriesForDisplay = null;
  2315. $sqlQuery = null;
  2316. if (! isset($_POST['adduser_submit']) && ! isset($_POST['change_copy'])) {
  2317. return [
  2318. $message,
  2319. $queries,
  2320. $queriesForDisplay,
  2321. $sqlQuery,
  2322. false, // Add user error
  2323. ];
  2324. }
  2325. $sqlQuery = '';
  2326. // Some reports where sent to the error reporting server with phpMyAdmin 5.1.0
  2327. // pred_username was reported to be not defined
  2328. $predUsername = $_POST['pred_username'] ?? '';
  2329. if ($predUsername === 'any') {
  2330. $username = '';
  2331. }
  2332. switch ($_POST['pred_hostname']) {
  2333. case 'any':
  2334. $hostname = '%';
  2335. break;
  2336. case 'localhost':
  2337. $hostname = 'localhost';
  2338. break;
  2339. case 'hosttable':
  2340. $hostname = '';
  2341. break;
  2342. case 'thishost':
  2343. $currentUserName = $this->dbi->fetchValue('SELECT USER()');
  2344. if ($currentUserName !== false) {
  2345. $hostname = mb_substr($currentUserName, mb_strrpos($currentUserName, '@') + 1);
  2346. unset($currentUserName);
  2347. }
  2348. break;
  2349. }
  2350. $sql = "SELECT '1' FROM `mysql`.`user`"
  2351. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  2352. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "';";
  2353. if ($this->dbi->fetchValue($sql) == 1) {
  2354. $message = Message::error(__('The user %s already exists!'));
  2355. $message->addParam('[em]\'' . $username . '\'@\'' . $hostname . '\'[/em]');
  2356. $_GET['adduser'] = true;
  2357. return [
  2358. $message,
  2359. $queries,
  2360. $queriesForDisplay,
  2361. $sqlQuery,
  2362. true, // Add user error
  2363. ];
  2364. }
  2365. [
  2366. $createUserReal,
  2367. $createUserShow,
  2368. $realSqlQuery,
  2369. $sqlQuery,
  2370. $passwordSetReal,
  2371. $passwordSetShow,
  2372. $alterRealSqlQuery,
  2373. $alterSqlQuery,
  2374. ] = $this->getSqlQueriesForDisplayAndAddUser($username, $hostname, ($password ?? ''));
  2375. if (empty($_POST['change_copy'])) {
  2376. $error = false;
  2377. if ($createUserReal !== null) {
  2378. if (! $this->dbi->tryQuery($createUserReal)) {
  2379. $error = true;
  2380. }
  2381. if (isset($passwordSetReal, $_POST['authentication_plugin']) && ! empty($passwordSetReal)) {
  2382. $this->setProperPasswordHashing($_POST['authentication_plugin']);
  2383. if ($this->dbi->tryQuery($passwordSetReal)) {
  2384. $sqlQuery .= $passwordSetShow;
  2385. }
  2386. }
  2387. $sqlQuery = $createUserShow . $sqlQuery;
  2388. }
  2389. [$sqlQuery, $message] = $this->addUserAndCreateDatabase(
  2390. $error,
  2391. $realSqlQuery,
  2392. $sqlQuery,
  2393. $username,
  2394. $hostname,
  2395. $dbname,
  2396. $alterRealSqlQuery,
  2397. $alterSqlQuery,
  2398. isset($_POST['createdb-1']),
  2399. isset($_POST['createdb-2']),
  2400. isset($_POST['createdb-3'])
  2401. );
  2402. if (! empty($_POST['userGroup']) && $isMenuwork) {
  2403. $this->setUserGroup($GLOBALS['username'], $_POST['userGroup']);
  2404. }
  2405. return [
  2406. $message,
  2407. $queries,
  2408. $queriesForDisplay,
  2409. $sqlQuery,
  2410. $error, // Add user error if the query fails
  2411. ];
  2412. }
  2413. // Copy the user group while copying a user
  2414. $oldUserGroup = $_POST['old_usergroup'] ?? null;
  2415. $this->setUserGroup($_POST['username'], $oldUserGroup);
  2416. if ($createUserReal !== null) {
  2417. $queries[] = $createUserReal;
  2418. }
  2419. $queries[] = $realSqlQuery;
  2420. if (isset($passwordSetReal, $_POST['authentication_plugin']) && ! empty($passwordSetReal)) {
  2421. $this->setProperPasswordHashing($_POST['authentication_plugin']);
  2422. $queries[] = $passwordSetReal;
  2423. }
  2424. // we put the query containing the hidden password in
  2425. // $queries_for_display, at the same position occupied
  2426. // by the real query in $queries
  2427. $tmpCount = count($queries);
  2428. if (isset($createUserReal)) {
  2429. $queriesForDisplay[$tmpCount - 2] = $createUserShow;
  2430. }
  2431. if (isset($passwordSetReal) && ! empty($passwordSetReal)) {
  2432. $queriesForDisplay[$tmpCount - 3] = $createUserShow;
  2433. $queriesForDisplay[$tmpCount - 2] = $sqlQuery;
  2434. $queriesForDisplay[$tmpCount - 1] = $passwordSetShow;
  2435. } else {
  2436. $queriesForDisplay[$tmpCount - 1] = $sqlQuery;
  2437. }
  2438. return [
  2439. $message,
  2440. $queries,
  2441. $queriesForDisplay,
  2442. $sqlQuery,
  2443. false, // Add user error
  2444. ];
  2445. }
  2446. /**
  2447. * Sets proper value of `old_passwords` according to
  2448. * the authentication plugin selected
  2449. *
  2450. * @param string $authPlugin authentication plugin selected
  2451. */
  2452. public function setProperPasswordHashing($authPlugin): void
  2453. {
  2454. // Set the hashing method used by PASSWORD()
  2455. // to be of type depending upon $authentication_plugin
  2456. if ($authPlugin === 'sha256_password') {
  2457. $this->dbi->tryQuery('SET `old_passwords` = 2;');
  2458. } elseif ($authPlugin === 'mysql_old_password') {
  2459. $this->dbi->tryQuery('SET `old_passwords` = 1;');
  2460. } else {
  2461. $this->dbi->tryQuery('SET `old_passwords` = 0;');
  2462. }
  2463. }
  2464. /**
  2465. * Update DB information: DB, Table, isWildcard
  2466. *
  2467. * @return array
  2468. */
  2469. public function getDataForDBInfo()
  2470. {
  2471. $username = null;
  2472. $hostname = null;
  2473. $dbname = null;
  2474. $tablename = null;
  2475. $routinename = null;
  2476. $returnDb = null;
  2477. if (isset($_REQUEST['username'])) {
  2478. $username = (string) $_REQUEST['username'];
  2479. }
  2480. if (isset($_REQUEST['hostname'])) {
  2481. $hostname = (string) $_REQUEST['hostname'];
  2482. }
  2483. /**
  2484. * Checks if a dropdown box has been used for selecting a database / table
  2485. */
  2486. if (
  2487. isset($_POST['pred_tablename'])
  2488. && is_scalar($_POST['pred_tablename'])
  2489. && strlen((string) $_POST['pred_tablename']) > 0
  2490. ) {
  2491. $tablename = (string) $_POST['pred_tablename'];
  2492. } elseif (
  2493. isset($_REQUEST['tablename'])
  2494. && is_scalar($_REQUEST['tablename'])
  2495. && strlen((string) $_REQUEST['tablename']) > 0
  2496. ) {
  2497. $tablename = (string) $_REQUEST['tablename'];
  2498. } else {
  2499. unset($tablename);
  2500. }
  2501. if (
  2502. isset($_POST['pred_routinename'])
  2503. && is_scalar($_POST['pred_routinename'])
  2504. && strlen((string) $_POST['pred_routinename']) > 0
  2505. ) {
  2506. $routinename = (string) $_POST['pred_routinename'];
  2507. } elseif (
  2508. isset($_REQUEST['routinename'])
  2509. && is_scalar($_REQUEST['routinename'])
  2510. && strlen((string) $_REQUEST['routinename']) > 0
  2511. ) {
  2512. $routinename = (string) $_REQUEST['routinename'];
  2513. } else {
  2514. unset($routinename);
  2515. }
  2516. if (isset($_POST['pred_dbname'])) {
  2517. $isValidPredDbname = true;
  2518. foreach ($_POST['pred_dbname'] as $key => $dbName) {
  2519. if (! isset($dbName) || ! is_scalar($dbName) || strlen((string) $dbName) === 0) {
  2520. $isValidPredDbname = false;
  2521. break;
  2522. }
  2523. }
  2524. }
  2525. if (isset($_REQUEST['dbname'])) {
  2526. $isValidDbname = true;
  2527. if (is_array($_REQUEST['dbname'])) {
  2528. foreach ($_REQUEST['dbname'] as $key => $dbName) {
  2529. if (! isset($dbName) || ! is_scalar($dbName) || strlen((string) $dbName) === 0) {
  2530. $isValidDbname = false;
  2531. break;
  2532. }
  2533. }
  2534. } else {
  2535. if (
  2536. ! isset($_REQUEST['dbname'])
  2537. || ! is_scalar($_REQUEST['dbname'])
  2538. || strlen((string) $_REQUEST['dbname']) === 0
  2539. ) {
  2540. $isValidDbname = false;
  2541. }
  2542. }
  2543. }
  2544. if (isset($isValidPredDbname) && $isValidPredDbname) {
  2545. $dbname = $_POST['pred_dbname'];
  2546. // If dbname contains only one database.
  2547. if (count($dbname) === 1) {
  2548. $dbname = $dbname[0];
  2549. }
  2550. } elseif (isset($isValidDbname) && $isValidDbname) {
  2551. $dbname = (string) $_REQUEST['dbname'];
  2552. } else {
  2553. unset($dbname, $tablename);
  2554. }
  2555. if (isset($dbname)) {
  2556. if (is_array($dbname)) {
  2557. $dbAndTable = $dbname;
  2558. $returnDb = $dbname;
  2559. foreach ($dbAndTable as $key => $dbName) {
  2560. $dbAndTable[$key] .= '.';
  2561. }
  2562. } else {
  2563. $unescapedDb = Util::unescapeMysqlWildcards($dbname);
  2564. $dbAndTable = Util::backquote($unescapedDb) . '.';
  2565. $returnDb = $dbname;
  2566. }
  2567. if (isset($tablename)) {
  2568. $dbAndTable .= Util::backquote($tablename);
  2569. } else {
  2570. if (is_array($dbAndTable)) {
  2571. foreach ($dbAndTable as $key => $dbName) {
  2572. $dbAndTable[$key] .= '*';
  2573. }
  2574. } else {
  2575. $dbAndTable .= '*';
  2576. }
  2577. }
  2578. } else {
  2579. $dbAndTable = '*.*';
  2580. }
  2581. // check if given $dbname is a wildcard or not
  2582. $databaseNameIsWildcard = ! is_array($dbname ?? '') && preg_match('/(?<!\\\\)(?:_|%)/', $dbname ?? '');
  2583. return [
  2584. $username,
  2585. $hostname,
  2586. $returnDb,
  2587. $tablename ?? null,
  2588. $routinename ?? null,
  2589. $dbAndTable,
  2590. $databaseNameIsWildcard,
  2591. ];
  2592. }
  2593. /**
  2594. * Get title and textarea for export user definition in Privileges
  2595. *
  2596. * @param string $username username
  2597. * @param string $hostname host name
  2598. *
  2599. * @return array ($title, $export)
  2600. */
  2601. public function getListForExportUserDefinition($username, $hostname)
  2602. {
  2603. $export = '<textarea class="export" cols="60" rows="15">';
  2604. /** @var array|null $selectedUsers */
  2605. $selectedUsers = $_POST['selected_usr'] ?? null;
  2606. if (isset($selectedUsers)) {
  2607. // export privileges for selected users
  2608. $title = __('Privileges');
  2609. //For removing duplicate entries of users
  2610. $selectedUsers = array_unique($selectedUsers);
  2611. foreach ($selectedUsers as $exportUser) {
  2612. $exportUsername = mb_substr(
  2613. $exportUser,
  2614. 0,
  2615. (int) mb_strpos($exportUser, '&')
  2616. );
  2617. $exportHostname = mb_substr(
  2618. $exportUser,
  2619. mb_strrpos($exportUser, ';') + 1
  2620. );
  2621. $export .= '# '
  2622. . sprintf(
  2623. __('Privileges for %s'),
  2624. '`' . htmlspecialchars($exportUsername)
  2625. . '`@`' . htmlspecialchars($exportHostname) . '`'
  2626. )
  2627. . "\n\n";
  2628. $export .= $this->getGrants($exportUsername, $exportHostname) . "\n";
  2629. }
  2630. } else {
  2631. // export privileges for a single user
  2632. $title = __('User') . ' `' . htmlspecialchars($username)
  2633. . '`@`' . htmlspecialchars($hostname) . '`';
  2634. $export .= $this->getGrants($username, $hostname);
  2635. }
  2636. // remove trailing whitespace
  2637. $export = trim($export);
  2638. $export .= '</textarea>';
  2639. return [
  2640. $title,
  2641. $export,
  2642. ];
  2643. }
  2644. /**
  2645. * Get HTML for display Add userfieldset
  2646. *
  2647. * @param string $db the database
  2648. * @param string $table the table name
  2649. *
  2650. * @return string html output
  2651. */
  2652. public function getAddUserHtmlFieldset($db = '', $table = '')
  2653. {
  2654. if (! $this->dbi->isCreateUser()) {
  2655. return '';
  2656. }
  2657. $relParams = [];
  2658. $urlParams = ['adduser' => 1];
  2659. if (! empty($db)) {
  2660. $urlParams['dbname'] = $relParams['checkprivsdb'] = $db;
  2661. }
  2662. if (! empty($table)) {
  2663. $urlParams['tablename'] = $relParams['checkprivstable'] = $table;
  2664. }
  2665. return $this->template->render('server/privileges/add_user_fieldset', [
  2666. 'url_params' => $urlParams,
  2667. 'rel_params' => $relParams,
  2668. ]);
  2669. }
  2670. /**
  2671. * Get HTML snippet for display user overview page
  2672. *
  2673. * @param string $textDir text directory
  2674. *
  2675. * @return string
  2676. */
  2677. public function getHtmlForUserOverview($textDir)
  2678. {
  2679. $passwordColumn = 'Password';
  2680. $serverVersion = $this->dbi->getVersion();
  2681. if (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50706) {
  2682. $passwordColumn = 'authentication_string';
  2683. }
  2684. // $sql_query is for the initial-filtered,
  2685. // $sql_query_all is for counting the total no. of users
  2686. $sqlQuery = $sqlQueryAll = 'SELECT *,' .
  2687. ' IF(`' . $passwordColumn . "` = _latin1 '', 'N', 'Y') AS 'Password'" .
  2688. ' FROM `mysql`.`user`';
  2689. $sqlQuery .= (isset($_GET['initial'])
  2690. ? $this->rangeOfUsers($_GET['initial'])
  2691. : '');
  2692. $sqlQuery .= ' ORDER BY `User` ASC, `Host` ASC;';
  2693. $sqlQueryAll .= ' ;';
  2694. $res = $this->dbi->tryQuery($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_STORE);
  2695. $resAll = $this->dbi->tryQuery($sqlQueryAll, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_STORE);
  2696. $errorMessages = '';
  2697. if (! $res) {
  2698. // the query failed! This may have two reasons:
  2699. // - the user does not have enough privileges
  2700. // - the privilege tables use a structure of an earlier version.
  2701. // so let's try a more simple query
  2702. $this->dbi->freeResult($res);
  2703. $this->dbi->freeResult($resAll);
  2704. $sqlQuery = 'SELECT * FROM `mysql`.`user`';
  2705. $res = $this->dbi->tryQuery($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_STORE);
  2706. if (! $res) {
  2707. $errorMessages .= $this->getHtmlForViewUsersError();
  2708. $errorMessages .= $this->getAddUserHtmlFieldset();
  2709. } else {
  2710. // This message is hardcoded because I will replace it by
  2711. // a automatic repair feature soon.
  2712. $raw = 'Your privilege table structure seems to be older than'
  2713. . ' this MySQL version!<br>'
  2714. . 'Please run the <code>mysql_upgrade</code> command'
  2715. . ' that should be included in your MySQL server distribution'
  2716. . ' to solve this problem!';
  2717. $errorMessages .= Message::rawError($raw)->getDisplay();
  2718. }
  2719. $this->dbi->freeResult($res);
  2720. } else {
  2721. $dbRights = $this->getDbRightsForUserOverview();
  2722. // for all initials, even non A-Z
  2723. $arrayInitials = [];
  2724. foreach ($dbRights as $right) {
  2725. foreach ($right as $account) {
  2726. if (empty($account['User']) && $account['Host'] === 'localhost') {
  2727. $emptyUserNotice = Message::notice(
  2728. __(
  2729. 'A user account allowing any user from localhost to '
  2730. . 'connect is present. This will prevent other users '
  2731. . 'from connecting if the host part of their account '
  2732. . 'allows a connection from any (%) host.'
  2733. )
  2734. . MySQLDocumentation::show('problems-connecting')
  2735. )->getDisplay();
  2736. break 2;
  2737. }
  2738. }
  2739. }
  2740. /**
  2741. * Displays the initials
  2742. * Also not necessary if there is less than 20 privileges
  2743. */
  2744. if ($this->dbi->numRows($resAll) > 20) {
  2745. $initials = $this->getHtmlForInitials($arrayInitials);
  2746. }
  2747. /**
  2748. * Display the user overview
  2749. * (if less than 50 users, display them immediately)
  2750. */
  2751. if (isset($_GET['initial']) || isset($_GET['showall']) || $this->dbi->numRows($res) < 50) {
  2752. $usersOverview = $this->getUsersOverview($res, $dbRights, $textDir);
  2753. $usersOverview .= $this->template->render('export_modal');
  2754. }
  2755. $response = ResponseRenderer::getInstance();
  2756. if (! $response->isAjax() || ! empty($_REQUEST['ajax_page_request'])) {
  2757. if ($GLOBALS['is_reload_priv']) {
  2758. $flushnote = new Message(
  2759. __(
  2760. 'Note: phpMyAdmin gets the users’ privileges directly '
  2761. . 'from MySQL’s privilege tables. The content of these '
  2762. . 'tables may differ from the privileges the server uses, '
  2763. . 'if they have been changed manually. In this case, '
  2764. . 'you should %sreload the privileges%s before you continue.'
  2765. ),
  2766. Message::NOTICE
  2767. );
  2768. $flushnote->addParamHtml(
  2769. '<a href="' . Url::getFromRoute('/server/privileges', ['flush_privileges' => 1])
  2770. . '" id="reload_privileges_anchor">'
  2771. );
  2772. $flushnote->addParamHtml('</a>');
  2773. } else {
  2774. $flushnote = new Message(
  2775. __(
  2776. 'Note: phpMyAdmin gets the users’ privileges directly '
  2777. . 'from MySQL’s privilege tables. The content of these '
  2778. . 'tables may differ from the privileges the server uses, '
  2779. . 'if they have been changed manually. In this case, '
  2780. . 'the privileges have to be reloaded but currently, you '
  2781. . 'don\'t have the RELOAD privilege.'
  2782. )
  2783. . MySQLDocumentation::show(
  2784. 'privileges-provided',
  2785. false,
  2786. null,
  2787. null,
  2788. 'priv_reload'
  2789. ),
  2790. Message::NOTICE
  2791. );
  2792. }
  2793. $flushNotice = $flushnote->getDisplay();
  2794. }
  2795. }
  2796. return $this->template->render('server/privileges/user_overview', [
  2797. 'error_messages' => $errorMessages,
  2798. 'empty_user_notice' => $emptyUserNotice ?? '',
  2799. 'initials' => $initials ?? '',
  2800. 'users_overview' => $usersOverview ?? '',
  2801. 'is_createuser' => $this->dbi->isCreateUser(),
  2802. 'flush_notice' => $flushNotice ?? '',
  2803. ]);
  2804. }
  2805. /**
  2806. * Get HTML snippet for display user properties
  2807. *
  2808. * @param bool $dbnameIsWildcard whether database name is wildcard or not
  2809. * @param string $urlDbname url database name that urlencode() string
  2810. * @param string $username username
  2811. * @param string $hostname host name
  2812. * @param string|array $dbname database name
  2813. * @param string $tablename table name
  2814. *
  2815. * @return string
  2816. */
  2817. public function getHtmlForUserProperties(
  2818. $dbnameIsWildcard,
  2819. $urlDbname,
  2820. $username,
  2821. $hostname,
  2822. $dbname,
  2823. $tablename
  2824. ) {
  2825. global $cfg;
  2826. $sql = "SELECT '1' FROM `mysql`.`user`"
  2827. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  2828. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "';";
  2829. $userDoesNotExists = (bool) ! $this->dbi->fetchValue($sql);
  2830. $loginInformationFields = '';
  2831. if ($userDoesNotExists) {
  2832. $loginInformationFields = $this->getHtmlForLoginInformationFields();
  2833. }
  2834. $params = [
  2835. 'username' => $username,
  2836. 'hostname' => $hostname,
  2837. ];
  2838. if (! is_array($dbname) && strlen($dbname) > 0) {
  2839. $params['dbname'] = $dbname;
  2840. if (strlen($tablename) > 0) {
  2841. $params['tablename'] = $tablename;
  2842. }
  2843. } else {
  2844. $params['dbname'] = $dbname;
  2845. }
  2846. $privilegesTable = $this->getHtmlToDisplayPrivilegesTable(
  2847. // If $dbname is an array, pass any one db as all have same privs.
  2848. is_string($dbname) && strlen($dbname) > 0
  2849. ? $dbname
  2850. : (is_array($dbname) ? (string) $dbname[0] : '*'),
  2851. strlen($tablename) > 0
  2852. ? $tablename
  2853. : '*'
  2854. );
  2855. $tableSpecificRights = '';
  2856. if (! is_array($dbname) && strlen($tablename) === 0 && empty($dbnameIsWildcard)) {
  2857. // no table name was given, display all table specific rights
  2858. // but only if $dbname contains no wildcards
  2859. if (strlen($dbname) === 0) {
  2860. $tableSpecificRights .= $this->getHtmlForAllTableSpecificRights($username, $hostname, 'database');
  2861. } else {
  2862. // unescape wildcards in dbname at table level
  2863. $unescapedDb = Util::unescapeMysqlWildcards($dbname);
  2864. $tableSpecificRights .= $this->getHtmlForAllTableSpecificRights(
  2865. $username,
  2866. $hostname,
  2867. 'table',
  2868. $unescapedDb
  2869. );
  2870. $tableSpecificRights .= $this->getHtmlForAllTableSpecificRights(
  2871. $username,
  2872. $hostname,
  2873. 'routine',
  2874. $unescapedDb
  2875. );
  2876. }
  2877. }
  2878. $databaseUrl = Util::getScriptNameForOption($cfg['DefaultTabDatabase'], 'database');
  2879. $databaseUrlTitle = Util::getTitleForTarget($cfg['DefaultTabDatabase']);
  2880. $tableUrl = Util::getScriptNameForOption($cfg['DefaultTabTable'], 'table');
  2881. $tableUrlTitle = Util::getTitleForTarget($cfg['DefaultTabTable']);
  2882. $changePassword = '';
  2883. $userGroup = '';
  2884. $changeLoginInfoFields = '';
  2885. if (! is_array($dbname) && strlen($dbname) === 0 && ! $userDoesNotExists) {
  2886. //change login information
  2887. $changePassword = $this->getFormForChangePassword($username, $hostname, true);
  2888. $userGroup = $this->getUserGroupForUser($username);
  2889. $changeLoginInfoFields = $this->getHtmlForLoginInformationFields('change', $username, $hostname);
  2890. }
  2891. return $this->template->render('server/privileges/user_properties', [
  2892. 'user_does_not_exists' => $userDoesNotExists,
  2893. 'login_information_fields' => $loginInformationFields,
  2894. 'params' => $params,
  2895. 'privileges_table' => $privilegesTable,
  2896. 'table_specific_rights' => $tableSpecificRights,
  2897. 'change_password' => $changePassword,
  2898. 'database' => $dbname,
  2899. 'dbname' => $urlDbname,
  2900. 'username' => $username,
  2901. 'hostname' => $hostname,
  2902. 'is_databases' => $dbnameIsWildcard || is_array($dbname) && count($dbname) > 1,
  2903. 'is_wildcard' => $dbnameIsWildcard,
  2904. 'table' => $tablename,
  2905. 'current_user' => $this->dbi->getCurrentUser(),
  2906. 'user_group' => $userGroup,
  2907. 'change_login_info_fields' => $changeLoginInfoFields,
  2908. 'database_url' => $databaseUrl,
  2909. 'database_url_title' => $databaseUrlTitle,
  2910. 'table_url' => $tableUrl,
  2911. 'table_url_title' => $tableUrlTitle,
  2912. ]);
  2913. }
  2914. /**
  2915. * Get queries for Table privileges to change or copy user
  2916. *
  2917. * @param string $userHostCondition user host condition to
  2918. * select relevant table privileges
  2919. * @param array $queries queries array
  2920. * @param string $username username
  2921. * @param string $hostname host name
  2922. *
  2923. * @return array
  2924. */
  2925. public function getTablePrivsQueriesForChangeOrCopyUser(
  2926. $userHostCondition,
  2927. array $queries,
  2928. $username,
  2929. $hostname
  2930. ) {
  2931. $res = $this->dbi->query(
  2932. 'SELECT `Db`, `Table_name`, `Table_priv` FROM `mysql`.`tables_priv`'
  2933. . $userHostCondition,
  2934. DatabaseInterface::CONNECT_USER,
  2935. DatabaseInterface::QUERY_STORE
  2936. );
  2937. while ($row = $this->dbi->fetchAssoc($res)) {
  2938. $res2 = $this->dbi->query(
  2939. 'SELECT `Column_name`, `Column_priv`'
  2940. . ' FROM `mysql`.`columns_priv`'
  2941. . ' WHERE `User`'
  2942. . ' = \'' . $this->dbi->escapeString($_POST['old_username']) . "'"
  2943. . ' AND `Host`'
  2944. . ' = \'' . $this->dbi->escapeString($_POST['old_username']) . '\''
  2945. . ' AND `Db`'
  2946. . ' = \'' . $this->dbi->escapeString($row['Db']) . "'"
  2947. . ' AND `Table_name`'
  2948. . ' = \'' . $this->dbi->escapeString($row['Table_name']) . "'"
  2949. . ';',
  2950. DatabaseInterface::CONNECT_USER,
  2951. DatabaseInterface::QUERY_STORE
  2952. );
  2953. $tmpPrivs1 = $this->extractPrivInfo($row);
  2954. $tmpPrivs2 = [
  2955. 'Select' => [],
  2956. 'Insert' => [],
  2957. 'Update' => [],
  2958. 'References' => [],
  2959. ];
  2960. while ($row2 = $this->dbi->fetchAssoc($res2)) {
  2961. $tmpArray = explode(',', $row2['Column_priv']);
  2962. if (in_array('Select', $tmpArray)) {
  2963. $tmpPrivs2['Select'][] = $row2['Column_name'];
  2964. }
  2965. if (in_array('Insert', $tmpArray)) {
  2966. $tmpPrivs2['Insert'][] = $row2['Column_name'];
  2967. }
  2968. if (in_array('Update', $tmpArray)) {
  2969. $tmpPrivs2['Update'][] = $row2['Column_name'];
  2970. }
  2971. if (! in_array('References', $tmpArray)) {
  2972. continue;
  2973. }
  2974. $tmpPrivs2['References'][] = $row2['Column_name'];
  2975. }
  2976. if (count($tmpPrivs2['Select']) > 0 && ! in_array('SELECT', $tmpPrivs1)) {
  2977. $tmpPrivs1[] = 'SELECT (`' . implode('`, `', $tmpPrivs2['Select']) . '`)';
  2978. }
  2979. if (count($tmpPrivs2['Insert']) > 0 && ! in_array('INSERT', $tmpPrivs1)) {
  2980. $tmpPrivs1[] = 'INSERT (`' . implode('`, `', $tmpPrivs2['Insert']) . '`)';
  2981. }
  2982. if (count($tmpPrivs2['Update']) > 0 && ! in_array('UPDATE', $tmpPrivs1)) {
  2983. $tmpPrivs1[] = 'UPDATE (`' . implode('`, `', $tmpPrivs2['Update']) . '`)';
  2984. }
  2985. if (count($tmpPrivs2['References']) > 0 && ! in_array('REFERENCES', $tmpPrivs1)) {
  2986. $tmpPrivs1[] = 'REFERENCES (`' . implode('`, `', $tmpPrivs2['References']) . '`)';
  2987. }
  2988. $queries[] = 'GRANT ' . implode(', ', $tmpPrivs1)
  2989. . ' ON ' . Util::backquote($row['Db']) . '.'
  2990. . Util::backquote($row['Table_name'])
  2991. . ' TO \'' . $this->dbi->escapeString($username)
  2992. . '\'@\'' . $this->dbi->escapeString($hostname) . '\''
  2993. . (in_array('Grant', explode(',', $row['Table_priv']))
  2994. ? ' WITH GRANT OPTION;'
  2995. : ';');
  2996. }
  2997. return $queries;
  2998. }
  2999. /**
  3000. * Get queries for database specific privileges for change or copy user
  3001. *
  3002. * @param array $queries queries array with string
  3003. * @param string $username username
  3004. * @param string $hostname host name
  3005. *
  3006. * @return array
  3007. */
  3008. public function getDbSpecificPrivsQueriesForChangeOrCopyUser(
  3009. array $queries,
  3010. $username,
  3011. $hostname
  3012. ) {
  3013. $userHostCondition = ' WHERE `User`'
  3014. . ' = \'' . $this->dbi->escapeString($_POST['old_username']) . "'"
  3015. . ' AND `Host`'
  3016. . ' = \'' . $this->dbi->escapeString($_POST['old_hostname']) . '\';';
  3017. $res = $this->dbi->query('SELECT * FROM `mysql`.`db`' . $userHostCondition);
  3018. while ($row = $this->dbi->fetchAssoc($res)) {
  3019. $queries[] = 'GRANT ' . implode(', ', $this->extractPrivInfo($row))
  3020. . ' ON ' . Util::backquote($row['Db']) . '.*'
  3021. . ' TO \'' . $this->dbi->escapeString($username)
  3022. . '\'@\'' . $this->dbi->escapeString($hostname) . '\''
  3023. . ($row['Grant_priv'] === 'Y' ? ' WITH GRANT OPTION;' : ';');
  3024. }
  3025. $this->dbi->freeResult($res);
  3026. $queries = $this->getTablePrivsQueriesForChangeOrCopyUser($userHostCondition, $queries, $username, $hostname);
  3027. return $queries;
  3028. }
  3029. /**
  3030. * Prepares queries for adding users and
  3031. * also create database and return query and message
  3032. *
  3033. * @param bool $error whether user create or not
  3034. * @param string $realSqlQuery SQL query for add a user
  3035. * @param string $sqlQuery SQL query to be displayed
  3036. * @param string $username username
  3037. * @param string $hostname host name
  3038. * @param string $dbname database name
  3039. * @param string $alterRealSqlQuery SQL query for ALTER USER
  3040. * @param string $alterSqlQuery SQL query for ALTER USER to be displayed
  3041. *
  3042. * @return array<int,string|Message>
  3043. */
  3044. public function addUserAndCreateDatabase(
  3045. $error,
  3046. $realSqlQuery,
  3047. $sqlQuery,
  3048. $username,
  3049. $hostname,
  3050. $dbname,
  3051. $alterRealSqlQuery,
  3052. $alterSqlQuery,
  3053. bool $createDb1,
  3054. bool $createDb2,
  3055. bool $createDb3
  3056. ): array {
  3057. if ($error || (! empty($realSqlQuery) && ! $this->dbi->tryQuery($realSqlQuery))) {
  3058. $createDb1 = $createDb2 = $createDb3 = false;
  3059. $message = Message::rawError((string) $this->dbi->getError());
  3060. } elseif ($alterRealSqlQuery !== '' && ! $this->dbi->tryQuery($alterRealSqlQuery)) {
  3061. $createDb1 = $createDb2 = $createDb3 = false;
  3062. $message = Message::rawError((string) $this->dbi->getError());
  3063. } else {
  3064. $sqlQuery .= $alterSqlQuery;
  3065. $message = Message::success(__('You have added a new user.'));
  3066. }
  3067. if ($createDb1) {
  3068. // Create database with same name and grant all privileges
  3069. $query = 'CREATE DATABASE IF NOT EXISTS '
  3070. . Util::backquote(
  3071. $this->dbi->escapeString($username)
  3072. ) . ';';
  3073. $sqlQuery .= $query;
  3074. if (! $this->dbi->tryQuery($query)) {
  3075. $message = Message::rawError((string) $this->dbi->getError());
  3076. }
  3077. /**
  3078. * Reload the navigation
  3079. */
  3080. $GLOBALS['reload'] = true;
  3081. $GLOBALS['db'] = $username;
  3082. $query = 'GRANT ALL PRIVILEGES ON '
  3083. . Util::backquote(
  3084. Util::escapeMysqlWildcards(
  3085. $this->dbi->escapeString($username)
  3086. )
  3087. ) . '.* TO \''
  3088. . $this->dbi->escapeString($username)
  3089. . '\'@\'' . $this->dbi->escapeString($hostname) . '\';';
  3090. $sqlQuery .= $query;
  3091. if (! $this->dbi->tryQuery($query)) {
  3092. $message = Message::rawError((string) $this->dbi->getError());
  3093. }
  3094. }
  3095. if ($createDb2) {
  3096. // Grant all privileges on wildcard name (username\_%)
  3097. $query = 'GRANT ALL PRIVILEGES ON '
  3098. . Util::backquote(
  3099. Util::escapeMysqlWildcards(
  3100. $this->dbi->escapeString($username)
  3101. ) . '\_%'
  3102. ) . '.* TO \''
  3103. . $this->dbi->escapeString($username)
  3104. . '\'@\'' . $this->dbi->escapeString($hostname) . '\';';
  3105. $sqlQuery .= $query;
  3106. if (! $this->dbi->tryQuery($query)) {
  3107. $message = Message::rawError((string) $this->dbi->getError());
  3108. }
  3109. }
  3110. if ($createDb3) {
  3111. // Grant all privileges on the specified database to the new user
  3112. $query = 'GRANT ALL PRIVILEGES ON '
  3113. . Util::backquote($dbname) . '.* TO \''
  3114. . $this->dbi->escapeString($username)
  3115. . '\'@\'' . $this->dbi->escapeString($hostname) . '\';';
  3116. $sqlQuery .= $query;
  3117. if (! $this->dbi->tryQuery($query)) {
  3118. $message = Message::rawError((string) $this->dbi->getError());
  3119. }
  3120. }
  3121. return [
  3122. $sqlQuery,
  3123. $message,
  3124. ];
  3125. }
  3126. /**
  3127. * Get the hashed string for password
  3128. *
  3129. * @param string $password password
  3130. *
  3131. * @return string
  3132. */
  3133. public function getHashedPassword($password)
  3134. {
  3135. $password = $this->dbi->escapeString($password);
  3136. $result = $this->dbi->fetchSingleRow("SELECT PASSWORD('" . $password . "') AS `password`;");
  3137. return $result['password'];
  3138. }
  3139. /**
  3140. * Check if MariaDB's 'simple_password_check'
  3141. * OR 'cracklib_password_check' is ACTIVE
  3142. */
  3143. public function checkIfMariaDBPwdCheckPluginActive(): bool
  3144. {
  3145. $serverVersion = $this->dbi->getVersion();
  3146. if (! (Compatibility::isMariaDb() && $serverVersion >= 100002)) {
  3147. return false;
  3148. }
  3149. $result = $this->dbi->tryQuery('SHOW PLUGINS SONAME LIKE \'%_password_check%\'');
  3150. /* Plugins are not working, for example directory does not exists */
  3151. if ($result === false) {
  3152. return false;
  3153. }
  3154. while ($row = $this->dbi->fetchAssoc($result)) {
  3155. if ($row['Status'] === 'ACTIVE') {
  3156. return true;
  3157. }
  3158. }
  3159. return false;
  3160. }
  3161. /**
  3162. * Get SQL queries for Display and Add user
  3163. *
  3164. * @param string $username username
  3165. * @param string $hostname host name
  3166. * @param string $password password
  3167. *
  3168. * @return array ($create_user_real, $create_user_show, $real_sql_query, $sql_query
  3169. * $password_set_real, $password_set_show, $alter_real_sql_query, $alter_sql_query)
  3170. */
  3171. public function getSqlQueriesForDisplayAndAddUser($username, $hostname, $password)
  3172. {
  3173. $slashedUsername = $this->dbi->escapeString($username);
  3174. $slashedHostname = $this->dbi->escapeString($hostname);
  3175. $slashedPassword = $this->dbi->escapeString($password);
  3176. $serverVersion = $this->dbi->getVersion();
  3177. $createUserStmt = sprintf('CREATE USER \'%s\'@\'%s\'', $slashedUsername, $slashedHostname);
  3178. $isMariaDBPwdPluginActive = $this->checkIfMariaDBPwdCheckPluginActive();
  3179. // See https://github.com/phpmyadmin/phpmyadmin/pull/11560#issuecomment-147158219
  3180. // for details regarding details of syntax usage for various versions
  3181. // 'IDENTIFIED WITH auth_plugin'
  3182. // is supported by MySQL 5.5.7+
  3183. if (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50507 && isset($_POST['authentication_plugin'])) {
  3184. $createUserStmt .= ' IDENTIFIED WITH '
  3185. . $_POST['authentication_plugin'];
  3186. }
  3187. // 'IDENTIFIED VIA auth_plugin'
  3188. // is supported by MariaDB 5.2+
  3189. if (
  3190. Compatibility::isMariaDb()
  3191. && $serverVersion >= 50200
  3192. && isset($_POST['authentication_plugin'])
  3193. && ! $isMariaDBPwdPluginActive
  3194. ) {
  3195. $createUserStmt .= ' IDENTIFIED VIA '
  3196. . $_POST['authentication_plugin'];
  3197. }
  3198. $createUserReal = $createUserStmt;
  3199. $createUserShow = $createUserStmt;
  3200. $passwordSetStmt = 'SET PASSWORD FOR \'%s\'@\'%s\' = \'%s\'';
  3201. $passwordSetShow = sprintf($passwordSetStmt, $slashedUsername, $slashedHostname, '***');
  3202. $sqlQueryStmt = sprintf(
  3203. 'GRANT %s ON *.* TO \'%s\'@\'%s\'',
  3204. implode(', ', $this->extractPrivInfo()),
  3205. $slashedUsername,
  3206. $slashedHostname
  3207. );
  3208. $realSqlQuery = $sqlQuery = $sqlQueryStmt;
  3209. // Set the proper hashing method
  3210. if (isset($_POST['authentication_plugin'])) {
  3211. $this->setProperPasswordHashing($_POST['authentication_plugin']);
  3212. }
  3213. // Use 'CREATE USER ... WITH ... AS ..' syntax for
  3214. // newer MySQL versions
  3215. // and 'CREATE USER ... VIA .. USING ..' syntax for
  3216. // newer MariaDB versions
  3217. if (
  3218. (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50706)
  3219. || (Compatibility::isMariaDb() && $serverVersion >= 50200)
  3220. ) {
  3221. $passwordSetReal = null;
  3222. // Required for binding '%' with '%s'
  3223. $createUserStmt = str_replace('%', '%%', $createUserStmt);
  3224. // MariaDB uses 'USING' whereas MySQL uses 'AS'
  3225. // but MariaDB with validation plugin needs cleartext password
  3226. if (Compatibility::isMariaDb() && ! $isMariaDBPwdPluginActive) {
  3227. $createUserStmt .= ' USING \'%s\'';
  3228. } elseif (Compatibility::isMariaDb()) {
  3229. $createUserStmt .= ' IDENTIFIED BY \'%s\'';
  3230. } elseif (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 80011) {
  3231. if (! str_contains($createUserStmt, 'IDENTIFIED')) {
  3232. // Maybe the authentication_plugin was not posted and then a part is missing
  3233. $createUserStmt .= ' IDENTIFIED BY \'%s\'';
  3234. } else {
  3235. $createUserStmt .= ' BY \'%s\'';
  3236. }
  3237. } else {
  3238. $createUserStmt .= ' AS \'%s\'';
  3239. }
  3240. if ($_POST['pred_password'] === 'keep') {
  3241. $createUserReal = sprintf($createUserStmt, $slashedPassword);
  3242. $createUserShow = sprintf($createUserStmt, '***');
  3243. } elseif ($_POST['pred_password'] === 'none') {
  3244. $createUserReal = sprintf($createUserStmt, null);
  3245. $createUserShow = sprintf($createUserStmt, '***');
  3246. } else {
  3247. if (
  3248. ! ((Compatibility::isMariaDb() && $isMariaDBPwdPluginActive)
  3249. || Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 80011)
  3250. ) {
  3251. $hashedPassword = $this->getHashedPassword($_POST['pma_pw']);
  3252. } else {
  3253. // MariaDB with validation plugin needs cleartext password
  3254. $hashedPassword = $_POST['pma_pw'];
  3255. }
  3256. $createUserReal = sprintf($createUserStmt, $hashedPassword);
  3257. $createUserShow = sprintf($createUserStmt, '***');
  3258. }
  3259. } else {
  3260. // Use 'SET PASSWORD' syntax for pre-5.7.6 MySQL versions
  3261. // and pre-5.2.0 MariaDB versions
  3262. if ($_POST['pred_password'] === 'keep') {
  3263. $passwordSetReal = sprintf($passwordSetStmt, $slashedUsername, $slashedHostname, $slashedPassword);
  3264. } elseif ($_POST['pred_password'] === 'none') {
  3265. $passwordSetReal = sprintf($passwordSetStmt, $slashedUsername, $slashedHostname, null);
  3266. } else {
  3267. $hashedPassword = $this->getHashedPassword($_POST['pma_pw']);
  3268. $passwordSetReal = sprintf($passwordSetStmt, $slashedUsername, $slashedHostname, $hashedPassword);
  3269. }
  3270. }
  3271. $alterRealSqlQuery = '';
  3272. $alterSqlQuery = '';
  3273. if (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 80011) {
  3274. $sqlQueryStmt = '';
  3275. if (
  3276. (isset($_POST['Grant_priv']) && $_POST['Grant_priv'] === 'Y')
  3277. || (isset($GLOBALS['Grant_priv']) && $GLOBALS['Grant_priv'] === 'Y')
  3278. ) {
  3279. $sqlQueryStmt = ' WITH GRANT OPTION';
  3280. }
  3281. $realSqlQuery .= $sqlQueryStmt;
  3282. $sqlQuery .= $sqlQueryStmt;
  3283. $alterSqlQueryStmt = sprintf('ALTER USER \'%s\'@\'%s\'', $slashedUsername, $slashedHostname);
  3284. $alterRealSqlQuery = $alterSqlQueryStmt;
  3285. $alterSqlQuery = $alterSqlQueryStmt;
  3286. }
  3287. // add REQUIRE clause
  3288. $requireClause = $this->getRequireClause();
  3289. $withClause = $this->getWithClauseForAddUserAndUpdatePrivs();
  3290. if (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 80011) {
  3291. $alterRealSqlQuery .= $requireClause;
  3292. $alterSqlQuery .= $requireClause;
  3293. $alterRealSqlQuery .= $withClause;
  3294. $alterSqlQuery .= $withClause;
  3295. } else {
  3296. $realSqlQuery .= $requireClause;
  3297. $sqlQuery .= $requireClause;
  3298. $realSqlQuery .= $withClause;
  3299. $sqlQuery .= $withClause;
  3300. }
  3301. if ($alterRealSqlQuery !== '') {
  3302. $alterRealSqlQuery .= ';';
  3303. $alterSqlQuery .= ';';
  3304. }
  3305. $createUserReal .= ';';
  3306. $createUserShow .= ';';
  3307. $realSqlQuery .= ';';
  3308. $sqlQuery .= ';';
  3309. // No Global GRANT_OPTION privilege
  3310. if (! $this->dbi->isGrantUser()) {
  3311. $realSqlQuery = '';
  3312. $sqlQuery = '';
  3313. }
  3314. // Use 'SET PASSWORD' for pre-5.7.6 MySQL versions
  3315. // and pre-5.2.0 MariaDB
  3316. if (
  3317. (Compatibility::isMySqlOrPerconaDb()
  3318. && $serverVersion >= 50706)
  3319. || (Compatibility::isMariaDb()
  3320. && $serverVersion >= 50200)
  3321. ) {
  3322. $passwordSetReal = null;
  3323. $passwordSetShow = null;
  3324. } else {
  3325. if ($passwordSetReal !== null) {
  3326. $passwordSetReal .= ';';
  3327. }
  3328. $passwordSetShow .= ';';
  3329. }
  3330. return [
  3331. $createUserReal,
  3332. $createUserShow,
  3333. $realSqlQuery,
  3334. $sqlQuery,
  3335. $passwordSetReal,
  3336. $passwordSetShow,
  3337. $alterRealSqlQuery,
  3338. $alterSqlQuery,
  3339. ];
  3340. }
  3341. /**
  3342. * Returns the type ('PROCEDURE' or 'FUNCTION') of the routine
  3343. *
  3344. * @param string $dbname database
  3345. * @param string $routineName routine
  3346. *
  3347. * @return string type
  3348. */
  3349. public function getRoutineType($dbname, $routineName)
  3350. {
  3351. $routineData = $this->dbi->getRoutines($dbname);
  3352. foreach ($routineData as $routine) {
  3353. if ($routine['name'] === $routineName) {
  3354. return $routine['type'];
  3355. }
  3356. }
  3357. return '';
  3358. }
  3359. /**
  3360. * @param string $username User name
  3361. * @param string $hostname Host name
  3362. * @param string $database Database name
  3363. * @param string $routine Routine name
  3364. *
  3365. * @return array
  3366. */
  3367. private function getRoutinePrivileges(
  3368. string $username,
  3369. string $hostname,
  3370. string $database,
  3371. string $routine
  3372. ): array {
  3373. $sql = 'SELECT `Proc_priv`'
  3374. . ' FROM `mysql`.`procs_priv`'
  3375. . " WHERE `User` = '" . $this->dbi->escapeString($username) . "'"
  3376. . " AND `Host` = '" . $this->dbi->escapeString($hostname) . "'"
  3377. . " AND `Db` = '"
  3378. . $this->dbi->escapeString(Util::unescapeMysqlWildcards($database)) . "'"
  3379. . " AND `Routine_name` LIKE '" . $this->dbi->escapeString($routine) . "';";
  3380. $privileges = $this->dbi->fetchValue($sql);
  3381. if ($privileges === false) {
  3382. $privileges = '';
  3383. }
  3384. return $this->parseProcPriv($privileges);
  3385. }
  3386. public function getFormForChangePassword(string $username, string $hostname, bool $editOthers): string
  3387. {
  3388. global $route;
  3389. $isPrivileges = $route === '/server/privileges';
  3390. $serverVersion = $this->dbi->getVersion();
  3391. $origAuthPlugin = $this->getCurrentAuthenticationPlugin('change', $username, $hostname);
  3392. $isNew = (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50507)
  3393. || (Compatibility::isMariaDb() && $serverVersion >= 50200);
  3394. $hasMoreAuthPlugins = (Compatibility::isMySqlOrPerconaDb() && $serverVersion >= 50706)
  3395. || ($this->dbi->isSuperUser() && $editOthers);
  3396. $activeAuthPlugins = ['mysql_native_password' => __('Native MySQL authentication')];
  3397. if ($isNew && $hasMoreAuthPlugins) {
  3398. $activeAuthPlugins = $this->plugins->getAuthentication();
  3399. if (isset($activeAuthPlugins['mysql_old_password'])) {
  3400. unset($activeAuthPlugins['mysql_old_password']);
  3401. }
  3402. }
  3403. return $this->template->render('server/privileges/change_password', [
  3404. 'username' => $username,
  3405. 'hostname' => $hostname,
  3406. 'is_privileges' => $isPrivileges,
  3407. 'is_new' => $isNew,
  3408. 'has_more_auth_plugins' => $hasMoreAuthPlugins,
  3409. 'active_auth_plugins' => $activeAuthPlugins,
  3410. 'orig_auth_plugin' => $origAuthPlugin,
  3411. ]);
  3412. }
  3413. /**
  3414. * @see https://dev.mysql.com/doc/refman/en/account-locking.html
  3415. * @see https://mariadb.com/kb/en/account-locking/
  3416. *
  3417. * @return array<string, string|null>|null
  3418. */
  3419. private function getUserPrivileges(string $user, string $host, bool $hasAccountLocking): ?array
  3420. {
  3421. $query = 'SELECT * FROM `mysql`.`user` WHERE `User` = ? AND `Host` = ?;';
  3422. /** @var mysqli_stmt|false $statement */
  3423. $statement = $this->dbi->prepare($query);
  3424. if ($statement === false || ! $statement->bind_param('ss', $user, $host) || ! $statement->execute()) {
  3425. return null;
  3426. }
  3427. $result = $statement->get_result();
  3428. $statement->close();
  3429. if ($result === false) {
  3430. return null;
  3431. }
  3432. /** @var array<string, string|null>|null $userPrivileges */
  3433. $userPrivileges = $this->dbi->fetchAssoc($result);
  3434. $this->dbi->freeResult($result);
  3435. if ($userPrivileges === null) {
  3436. return null;
  3437. }
  3438. if (! $hasAccountLocking || ! $this->dbi->isMariaDB()) {
  3439. return $userPrivileges;
  3440. }
  3441. $userPrivileges['account_locked'] = 'N';
  3442. $query = 'SELECT * FROM `mysql`.`global_priv` WHERE `User` = ? AND `Host` = ?;';
  3443. /** @var mysqli_stmt|false $statement */
  3444. $statement = $this->dbi->prepare($query);
  3445. if ($statement === false || ! $statement->bind_param('ss', $user, $host) || ! $statement->execute()) {
  3446. return $userPrivileges;
  3447. }
  3448. $result = $statement->get_result();
  3449. $statement->close();
  3450. if ($result === false) {
  3451. return $userPrivileges;
  3452. }
  3453. /** @var array<string, string|null>|null $globalPrivileges */
  3454. $globalPrivileges = $this->dbi->fetchAssoc($result);
  3455. $this->dbi->freeResult($result);
  3456. if ($globalPrivileges === null) {
  3457. return $userPrivileges;
  3458. }
  3459. $privileges = json_decode($globalPrivileges['Priv'] ?? '[]', true);
  3460. if (! is_array($privileges)) {
  3461. return $userPrivileges;
  3462. }
  3463. if (isset($privileges['account_locked']) && $privileges['account_locked']) {
  3464. $userPrivileges['account_locked'] = 'Y';
  3465. }
  3466. return $userPrivileges;
  3467. }
  3468. }