MySQL.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Setup;
  8. use Doctrine\DBAL\Platforms\MySQL80Platform;
  9. use OC\DB\ConnectionAdapter;
  10. use OC\DB\MySqlTools;
  11. use OCP\IDBConnection;
  12. use OCP\Security\ISecureRandom;
  13. class MySQL extends AbstractDatabase {
  14. public $dbprettyname = 'MySQL/MariaDB';
  15. public function setupDatabase($username) {
  16. //check if the database user has admin right
  17. $connection = $this->connect(['dbname' => null]);
  18. // detect mb4
  19. $tools = new MySqlTools();
  20. if ($tools->supports4ByteCharset(new ConnectionAdapter($connection))) {
  21. $this->config->setValue('mysql.utf8mb4', true);
  22. $connection = $this->connect(['dbname' => null]);
  23. }
  24. if ($this->tryCreateDbUser) {
  25. $this->createSpecificUser($username, new ConnectionAdapter($connection));
  26. }
  27. $this->config->setValues([
  28. 'dbuser' => $this->dbUser,
  29. 'dbpassword' => $this->dbPassword,
  30. ]);
  31. //create the database
  32. $this->createDatabase($connection);
  33. //fill the database if needed
  34. $query = 'select count(*) from information_schema.tables where table_schema=? AND table_name = ?';
  35. $connection->executeQuery($query, [$this->dbName, $this->tablePrefix . 'users']);
  36. $connection->close();
  37. $connection = $this->connect();
  38. try {
  39. $connection->connect();
  40. } catch (\Exception $e) {
  41. $this->logger->error($e->getMessage(), [
  42. 'exception' => $e,
  43. ]);
  44. throw new \OC\DatabaseSetupException($this->trans->t('MySQL Login and/or password not valid'),
  45. $this->trans->t('You need to enter details of an existing account.'), 0, $e);
  46. }
  47. }
  48. /**
  49. * @param \OC\DB\Connection $connection
  50. */
  51. private function createDatabase($connection) {
  52. try {
  53. $name = $this->dbName;
  54. $user = $this->dbUser;
  55. //we can't use OC_DB functions here because we need to connect as the administrative user.
  56. $characterSet = $this->config->getValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
  57. $query = "CREATE DATABASE IF NOT EXISTS `$name` CHARACTER SET $characterSet COLLATE {$characterSet}_bin;";
  58. $connection->executeUpdate($query);
  59. } catch (\Exception $ex) {
  60. $this->logger->error('Database creation failed.', [
  61. 'exception' => $ex,
  62. 'app' => 'mysql.setup',
  63. ]);
  64. return;
  65. }
  66. try {
  67. //this query will fail if there aren't the right permissions, ignore the error
  68. $query = "GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, REFERENCES, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, EVENT, TRIGGER ON `$name` . * TO '$user'";
  69. $connection->executeUpdate($query);
  70. } catch (\Exception $ex) {
  71. $this->logger->debug('Could not automatically grant privileges, this can be ignored if database user already had privileges.', [
  72. 'exception' => $ex,
  73. 'app' => 'mysql.setup',
  74. ]);
  75. }
  76. }
  77. /**
  78. * @param IDBConnection $connection
  79. * @throws \OC\DatabaseSetupException
  80. */
  81. private function createDBUser($connection) {
  82. try {
  83. $name = $this->dbUser;
  84. $password = $this->dbPassword;
  85. // we need to create 2 accounts, one for global use and one for local user. if we don't specify the local one,
  86. // the anonymous user would take precedence when there is one.
  87. if ($connection->getDatabasePlatform() instanceof Mysql80Platform) {
  88. $query = "CREATE USER '$name'@'localhost' IDENTIFIED WITH mysql_native_password BY '$password'";
  89. $connection->executeUpdate($query);
  90. $query = "CREATE USER '$name'@'%' IDENTIFIED WITH mysql_native_password BY '$password'";
  91. $connection->executeUpdate($query);
  92. } else {
  93. $query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
  94. $connection->executeUpdate($query);
  95. $query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
  96. $connection->executeUpdate($query);
  97. }
  98. } catch (\Exception $ex) {
  99. $this->logger->error('Database user creation failed.', [
  100. 'exception' => $ex,
  101. 'app' => 'mysql.setup',
  102. ]);
  103. throw $ex;
  104. }
  105. }
  106. /**
  107. * @param $username
  108. * @param IDBConnection $connection
  109. */
  110. private function createSpecificUser($username, $connection): void {
  111. $rootUser = $this->dbUser;
  112. $rootPassword = $this->dbPassword;
  113. //create a random password so we don't need to store the admin password in the config file
  114. $saveSymbols = str_replace(['\"', '\\', '\'', '`'], '', ISecureRandom::CHAR_SYMBOLS);
  115. $password = $this->random->generate(22, ISecureRandom::CHAR_ALPHANUMERIC . $saveSymbols)
  116. . $this->random->generate(2, ISecureRandom::CHAR_UPPER)
  117. . $this->random->generate(2, ISecureRandom::CHAR_LOWER)
  118. . $this->random->generate(2, ISecureRandom::CHAR_DIGITS)
  119. . $this->random->generate(2, $saveSymbols);
  120. $this->dbPassword = str_shuffle($password);
  121. try {
  122. //user already specified in config
  123. $oldUser = $this->config->getValue('dbuser', false);
  124. //we don't have a dbuser specified in config
  125. if ($this->dbUser !== $oldUser) {
  126. //add prefix to the admin username to prevent collisions
  127. $adminUser = substr('oc_' . $username, 0, 16);
  128. $i = 1;
  129. while (true) {
  130. //this should be enough to check for admin rights in mysql
  131. $query = 'SELECT user FROM mysql.user WHERE user=?';
  132. $result = $connection->executeQuery($query, [$adminUser]);
  133. //current dbuser has admin rights
  134. $data = $result->fetchAll();
  135. $result->closeCursor();
  136. //new dbuser does not exist
  137. if (count($data) === 0) {
  138. //use the admin login data for the new database user
  139. $this->dbUser = $adminUser;
  140. $this->createDBUser($connection);
  141. break;
  142. } else {
  143. //repeat with different username
  144. $length = strlen((string)$i);
  145. $adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
  146. $i++;
  147. }
  148. }
  149. } else {
  150. // Reuse existing password if a database config is already present
  151. $this->dbPassword = $rootPassword;
  152. }
  153. } catch (\Exception $ex) {
  154. $this->logger->info('Can not create a new MySQL user, will continue with the provided user.', [
  155. 'exception' => $ex,
  156. 'app' => 'mysql.setup',
  157. ]);
  158. // Restore the original credentials
  159. $this->dbUser = $rootUser;
  160. $this->dbPassword = $rootPassword;
  161. }
  162. }
  163. }