PostgreSQL.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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 OC\DatabaseException;
  9. use OC\DB\Connection;
  10. use OC\DB\QueryBuilder\Literal;
  11. use OCP\Security\ISecureRandom;
  12. class PostgreSQL extends AbstractDatabase {
  13. public $dbprettyname = 'PostgreSQL';
  14. /**
  15. * @param string $username
  16. * @throws \OC\DatabaseSetupException
  17. */
  18. public function setupDatabase($username) {
  19. try {
  20. $connection = $this->connect([
  21. 'dbname' => 'postgres'
  22. ]);
  23. if ($this->tryCreateDbUser) {
  24. //check for roles creation rights in postgresql
  25. $builder = $connection->getQueryBuilder();
  26. $builder->automaticTablePrefix(false);
  27. $query = $builder
  28. ->select('rolname')
  29. ->from('pg_roles')
  30. ->where($builder->expr()->eq('rolcreaterole', new Literal('TRUE')))
  31. ->andWhere($builder->expr()->eq('rolname', $builder->createNamedParameter($this->dbUser)));
  32. try {
  33. $result = $query->execute();
  34. $canCreateRoles = $result->rowCount() > 0;
  35. } catch (DatabaseException $e) {
  36. $canCreateRoles = false;
  37. }
  38. if ($canCreateRoles) {
  39. $connectionMainDatabase = $this->connect();
  40. //use the admin login data for the new database user
  41. //add prefix to the postgresql user name to prevent collisions
  42. $this->dbUser = 'oc_' . strtolower($username);
  43. //create a new password so we don't need to store the admin config in the config file
  44. $this->dbPassword = \OC::$server->get(ISecureRandom::class)->generate(30, ISecureRandom::CHAR_ALPHANUMERIC);
  45. $this->createDBUser($connection);
  46. // Go to the main database and grant create on the public schema
  47. // The code below is implemented to make installing possible with PostgreSQL version 15:
  48. // https://www.postgresql.org/docs/release/15.0/
  49. // From the release notes: For new databases having no need to defend against insider threats, granting CREATE permission will yield the behavior of prior releases
  50. // Therefore we assume that the database is only used by one user/service which is Nextcloud
  51. // Additional services should get installed in a separate database in order to stay secure
  52. // Also see https://www.postgresql.org/docs/15/ddl-schemas.html#DDL-SCHEMAS-PATTERNS
  53. $connectionMainDatabase->executeQuery('GRANT CREATE ON SCHEMA public TO "' . addslashes($this->dbUser) . '"');
  54. $connectionMainDatabase->close();
  55. }
  56. }
  57. $this->config->setValues([
  58. 'dbuser' => $this->dbUser,
  59. 'dbpassword' => $this->dbPassword,
  60. ]);
  61. //create the database
  62. $this->createDatabase($connection);
  63. // the connection to dbname=postgres is not needed anymore
  64. $connection->close();
  65. } catch (\Exception $e) {
  66. $this->logger->warning('Error trying to connect as "postgres", assuming database is setup and tables need to be created', [
  67. 'exception' => $e,
  68. ]);
  69. $this->config->setValues([
  70. 'dbuser' => $this->dbUser,
  71. 'dbpassword' => $this->dbPassword,
  72. ]);
  73. }
  74. // connect to the database (dbname=$this->dbname) and check if it needs to be filled
  75. $this->dbUser = $this->config->getValue('dbuser');
  76. $this->dbPassword = $this->config->getValue('dbpassword');
  77. $connection = $this->connect();
  78. try {
  79. $connection->connect();
  80. } catch (\Exception $e) {
  81. $this->logger->error($e->getMessage(), [
  82. 'exception' => $e,
  83. ]);
  84. throw new \OC\DatabaseSetupException($this->trans->t('PostgreSQL Login and/or password not valid'),
  85. $this->trans->t('You need to enter details of an existing account.'), 0, $e);
  86. }
  87. }
  88. private function createDatabase(Connection $connection) {
  89. if (!$this->databaseExists($connection)) {
  90. //The database does not exists... let's create it
  91. $query = $connection->prepare("CREATE DATABASE " . addslashes($this->dbName) . " OWNER \"" . addslashes($this->dbUser) . '"');
  92. try {
  93. $query->execute();
  94. } catch (DatabaseException $e) {
  95. $this->logger->error('Error while trying to create database', [
  96. 'exception' => $e,
  97. ]);
  98. }
  99. } else {
  100. $query = $connection->prepare("REVOKE ALL PRIVILEGES ON DATABASE " . addslashes($this->dbName) . " FROM PUBLIC");
  101. try {
  102. $query->execute();
  103. } catch (DatabaseException $e) {
  104. $this->logger->error('Error while trying to restrict database permissions', [
  105. 'exception' => $e,
  106. ]);
  107. }
  108. }
  109. }
  110. private function userExists(Connection $connection) {
  111. $builder = $connection->getQueryBuilder();
  112. $builder->automaticTablePrefix(false);
  113. $query = $builder->select('*')
  114. ->from('pg_roles')
  115. ->where($builder->expr()->eq('rolname', $builder->createNamedParameter($this->dbUser)));
  116. $result = $query->execute();
  117. return $result->rowCount() > 0;
  118. }
  119. private function databaseExists(Connection $connection) {
  120. $builder = $connection->getQueryBuilder();
  121. $builder->automaticTablePrefix(false);
  122. $query = $builder->select('datname')
  123. ->from('pg_database')
  124. ->where($builder->expr()->eq('datname', $builder->createNamedParameter($this->dbName)));
  125. $result = $query->execute();
  126. return $result->rowCount() > 0;
  127. }
  128. private function createDBUser(Connection $connection) {
  129. $dbUser = $this->dbUser;
  130. try {
  131. $i = 1;
  132. while ($this->userExists($connection)) {
  133. $i++;
  134. $this->dbUser = $dbUser . $i;
  135. }
  136. // create the user
  137. $query = $connection->prepare("CREATE USER \"" . addslashes($this->dbUser) . "\" CREATEDB PASSWORD '" . addslashes($this->dbPassword) . "'");
  138. $query->execute();
  139. if ($this->databaseExists($connection)) {
  140. $query = $connection->prepare('GRANT CONNECT ON DATABASE ' . addslashes($this->dbName) . ' TO "' . addslashes($this->dbUser) . '"');
  141. $query->execute();
  142. }
  143. } catch (DatabaseException $e) {
  144. $this->logger->error('Error while trying to create database user', [
  145. 'exception' => $e,
  146. ]);
  147. }
  148. }
  149. }