diff --git a/app/Services/Databases/DatabaseHostGateway.php b/app/Services/Databases/DatabaseHostGateway.php index bcf4c2e4f..2ea8bca71 100644 --- a/app/Services/Databases/DatabaseHostGateway.php +++ b/app/Services/Databases/DatabaseHostGateway.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace Pterodactyl\Services\Databases; +use Illuminate\Database\Connection; use Illuminate\Support\Facades\DB; /** @@ -27,7 +28,7 @@ class DatabaseHostGateway */ public function createDatabase(string $database): bool { - return $this->run(sprintf('CREATE DATABASE IF NOT EXISTS `%s`', $database)); + return $this->run(sprintf('CREATE DATABASE IF NOT EXISTS %s', $this->identifier($database))); } /** @@ -35,15 +36,17 @@ class DatabaseHostGateway */ public function createUser(string $username, string $remote, string $password, ?int $maxConnections): bool { - $args = [$username, $remote, $password]; - $command = "CREATE USER `%s`@`%s` IDENTIFIED BY '%s'"; + $statement = sprintf( + 'CREATE USER %s IDENTIFIED BY %s', + $this->account($username, $remote), + $this->connection()->escape($password), + ); if (! empty($maxConnections)) { - $args[] = $maxConnections; - $command .= ' WITH MAX_USER_CONNECTIONS %s'; + $statement .= sprintf(' WITH MAX_USER_CONNECTIONS %d', $maxConnections); } - return $this->run(sprintf($command, ...$args)); + return $this->run($statement); } /** @@ -52,10 +55,9 @@ class DatabaseHostGateway public function assignUserToDatabase(string $database, string $username, string $remote): bool { return $this->run(sprintf( - 'GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, REFERENCES, INDEX, LOCK TABLES, CREATE ROUTINE, ALTER ROUTINE, EXECUTE, CREATE TEMPORARY TABLES, CREATE VIEW, SHOW VIEW, EVENT, TRIGGER ON `%s`.* TO `%s`@`%s`', - $database, - $username, - $remote + 'GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, REFERENCES, INDEX, LOCK TABLES, CREATE ROUTINE, ALTER ROUTINE, EXECUTE, CREATE TEMPORARY TABLES, CREATE VIEW, SHOW VIEW, EVENT, TRIGGER ON %s.* TO %s', + $this->identifier($this->grantableDatabaseName($database)), + $this->account($username, $remote), )); } @@ -72,7 +74,7 @@ class DatabaseHostGateway */ public function dropDatabase(string $database): bool { - return $this->run(sprintf('DROP DATABASE IF EXISTS `%s`', $database)); + return $this->connection()->getSchemaBuilder()->dropDatabaseIfExists($database); } /** @@ -80,11 +82,53 @@ class DatabaseHostGateway */ public function dropUser(string $username, string $remote): bool { - return $this->run(sprintf('DROP USER IF EXISTS `%s`@`%s`', $username, $remote)); + return $this->run(sprintf('DROP USER IF EXISTS %s', $this->account($username, $remote))); + } + + /** + * Return the database name to use in a GRANT statement. "_" and "%" are pattern + * characters in a database-level grant unless MySQL has partial_revokes enabled. + */ + private function grantableDatabaseName(string $database): string + { + return $this->grantsUseWildcards() ? addcslashes($database, '\\_%') : $database; + } + + /** + * Determine if the host reads wildcards in database-level grants. MariaDB, and MySQL + * before 8.0.16, have no partial_revokes and always do. + */ + private function grantsUseWildcards(): bool + { + $variables = $this->connection()->select("SHOW GLOBAL VARIABLES LIKE 'partial\\_revokes'"); + + return data_get($variables, '0.Value') !== 'ON'; + } + + /** + * Quote an account name, such as `user`@`host`. + */ + private function account(string $username, string $remote): string + { + return $this->identifier($username).'@'.$this->identifier($remote); + } + + /** + * Quote a MySQL identifier. The query grammar's wrap() can't be used here because it + * splits on dots, and remotes such as 10.0.0.% contain them. + */ + private function identifier(string $value): string + { + return '`'.str_replace('`', '``', $value).'`'; + } + + private function connection(): Connection + { + return DB::connection($this->getConnection()); } private function run(string $statement): bool { - return DB::connection($this->getConnection())->statement($statement); + return $this->connection()->statement($statement); } } diff --git a/tests/Integration/Services/Databases/DatabaseHostGatewayTest.php b/tests/Integration/Services/Databases/DatabaseHostGatewayTest.php new file mode 100644 index 000000000..958d2ddb4 --- /dev/null +++ b/tests/Integration/Services/Databases/DatabaseHostGatewayTest.php @@ -0,0 +1,135 @@ +set('database.connections.'.DatabaseHostGateway::DEFAULT_CONNECTION_NAME, config('database.connections.mysql')); + + $this->gateway = new DatabaseHostGateway(); + $this->databases = []; + $this->users = []; +}); + +afterEach(function (): void { + DB::purge(LOGIN_CONNECTION); + + foreach ($this->users as [$username, $remote]) { + $this->gateway->dropUser($username, $remote); + } + + foreach ($this->databases as $database) { + $this->gateway->dropDatabase($database); + } + + DB::purge(DatabaseHostGateway::DEFAULT_CONNECTION_NAME); +}); + +test('a grant only matches the exact database name', function (): void { + assertGrantIsIsolated($this); +}); + +test('a grant only matches the exact database name with partial_revokes enabled', function (): void { + $connection = DB::connection(DatabaseHostGateway::DEFAULT_CONNECTION_NAME); + if ($connection instanceof MySqlConnection && $connection->isMaria()) { + $this->markTestSkipped('MariaDB has no partial_revokes.'); + } + + $original = (bool) $connection->scalar('SELECT @@global.partial_revokes'); + $connection->statement('SET GLOBAL partial_revokes = ON'); + DB::purge(DatabaseHostGateway::DEFAULT_CONNECTION_NAME); + + try { + assertGrantIsIsolated($this); + } finally { + DB::connection(DatabaseHostGateway::DEFAULT_CONNECTION_NAME)->statement('SET GLOBAL partial_revokes = '.($original ? 'ON' : 'OFF')); + } +}); + +test('identifiers and passwords are quoted', function (): void { + $suffix = Str::lower(Str::random(8)); + $database = createHostDatabase($this, "odd`name_{$suffix}"); + $username = 'q_'.$suffix; + $remote = '10.0.0.%'; + + expect($this->gateway->createUser($username, $remote, "it's a \\ `pass` \"word\"", 5))->toBeTrue(); + $this->users[] = [$username, $remote]; + expect($this->gateway->assignUserToDatabase($database, $username, $remote))->toBeTrue(); + + $connection = DB::connection(DatabaseHostGateway::DEFAULT_CONNECTION_NAME); + expect($connection->scalar('SELECT COUNT(*) FROM information_schema.schemata WHERE schema_name = ?', [$database]))->toEqual(1) + ->and($connection->scalar('SELECT max_user_connections FROM mysql.user WHERE User = ? AND Host = ?', [$username, $remote]))->toEqual(5); + + expect($this->gateway->dropUser($username, $remote))->toBeTrue() + ->and($connection->scalar('SELECT COUNT(*) FROM mysql.user WHERE User = ?', [$username]))->toEqual(0); +}); + +/** + * A grant on a database name containing "_" applies to that name only. + */ +function assertGrantIsIsolated(object $test): void +{ + $suffix = Str::lower(Str::random(8)); + $other = createHostDatabase($test, "gx{$suffix}"); + $own = createHostDatabase($test, "g_{$suffix}"); + + // Use the host the server sees this client as, so an anonymous ''@'localhost' account on + // a local server can't take precedence over a '%' remote. + $remote = Str::afterLast((string) DB::connection(DatabaseHostGateway::DEFAULT_CONNECTION_NAME)->scalar('SELECT USER()'), '@'); + $username = 'u_'.$suffix; + $password = "it's-".Str::random(16); + expect($test->gateway->createUser($username, $remote, $password, null))->toBeTrue(); + $test->users[] = [$username, $remote]; + expect($test->gateway->assignUserToDatabase($own, $username, $remote))->toBeTrue(); + $test->gateway->flush(); + + $login = login($username, $password, $own); + + $login->statement("CREATE TABLE `{$own}`.`owned` (`id` INT)"); + + expect($login->scalar("SELECT COUNT(*) FROM `{$own}`.`owned`"))->toEqual(0); + + $visible = array_map(fn (object $row) => $row->Database, $login->select('SHOW DATABASES')); + expect($visible)->toContain($own)->not->toContain($other); + + expect(fn () => $login->statement("CREATE TABLE `{$other}`.`other` (`id` INT)")) + ->toThrow(QueryException::class, 'denied'); +} + +function createHostDatabase(object $test, string $name): string +{ + expect($test->gateway->createDatabase($name))->toBeTrue(); + $test->databases[] = $name; + + return $name; +} + +function login(string $username, string $password, string $database): Connection +{ + DB::purge(LOGIN_CONNECTION); + config()->set('database.connections.'.LOGIN_CONNECTION, [ + ...config('database.connections.mysql'), + 'username' => $username, + 'password' => $password, + 'database' => $database, + ]); + + return DB::connection(LOGIN_CONNECTION); +}