From a463294b8dfd395741948abf0862cbe44532dd72 Mon Sep 17 00:00:00 2001 From: Hannes Papenberg Date: Fri, 13 Nov 2026 06:44:18 +0100 Subject: [PATCH] Validate column definitions from import files The importers put the column type, the Extra attributes, the key Sub_part and generated defaults from the XML into DDL as they were, so a crafted export file run through mergeStructure() or the import command could execute arbitrary SQL. Column types must now be plain type declarations, Extra may only contain the attributes MySQL reports, Sub_part is cast to int, and defaults that are not a known expression are quoted. The CREATE statements are split with splitSql() instead of explode(';'), so a semicolon in a quoted default no longer breaks them. The class docblock says that import files must be trusted. Co-Authored-By: Claude Opus 5.5 --- Tests/Mysqli/MysqliImporterTest.php | 59 +++++++++++++++++++++++++++++ src/DatabaseImporter.php | 33 +++++++++++++++- src/Mysql/MysqlImporter.php | 14 ++++++- src/Mysqli/MysqliImporter.php | 14 ++++++- src/Pgsql/PgsqlImporter.php | 9 ++++- 5 files changed, 122 insertions(+), 7 deletions(-) diff --git a/Tests/Mysqli/MysqliImporterTest.php b/Tests/Mysqli/MysqliImporterTest.php index 7e24354c..5bca646d 100644 --- a/Tests/Mysqli/MysqliImporterTest.php +++ b/Tests/Mysqli/MysqliImporterTest.php @@ -382,4 +382,63 @@ public function testCheck(?string $db, $from, ?string $exceptionMessage) $this->assertSame($importer, $importer->check(), 'The importer supports method chaining'); } + + #[TestDox('SQL in the column type or attributes of an import file is rejected')] + public function testInjectedColumnDefinitionIsRejected() + { + $importer = new MysqliImporter(); + $importer->setDbo($this->db); + + $method = new \ReflectionMethod($importer, 'getColumnSql'); + + foreach ( + [ + '', + '', + ] as $field + ) { + try { + $method->invoke($importer, new \SimpleXMLElement($field)); + $this->fail('Expected the column definition to be rejected: ' . $field); + } catch (\RuntimeException $e) { + $this->assertStringContainsString('in the import file', $e->getMessage()); + } + } + + $this->assertSame( + '`a` enum(' . "'x','y'" . ') NOT NULL DEFAULT ' . "'x'", + $method->invoke($importer, new \SimpleXMLElement('')), + 'Valid types are still accepted' + ); + } + + #[TestDox('A semicolon in a default value does not split the CREATE TABLE statement')] + public function testSemicolonInDefaultKeepsStatementTogether() + { + $queries = []; + + $db = $this->createStub(MysqliDriver::class); + $db->method('getPrefix')->willReturn('jos_'); + $db->method('getTableList')->willReturn([]); + $db->method('quote')->willReturnCallback(fn ($text) => "'" . str_replace("'", "''", $text) . "'"); + $db->method('quoteName')->willReturnCallback(fn ($name) => '`' . $name . '`'); + $db->method('setQuery')->willReturnCallback( + function ($query) use (&$queries, $db) { + $queries[] = (string) $query; + + return $db; + } + ); + + $xml = '' + . '' + . ''; + + $importer = new MysqliImporter(); + $importer->setDbo($db)->from($xml)->asXml()->mergeStructure(); + + $this->assertCount(1, $queries); + $this->assertStringContainsString("DEFAULT 'x;y'", $queries[0]); + } } + diff --git a/src/DatabaseImporter.php b/src/DatabaseImporter.php index c8fc1021..22498d51 100644 --- a/src/DatabaseImporter.php +++ b/src/DatabaseImporter.php @@ -12,6 +12,9 @@ /** * Joomla Framework Database Importer Class * + * Import files must come from a trusted source. Column types and attributes are validated, but parts of the + * structure, such as the index definitions in PostgreSQL exports, are executed as SQL. + * * @since 1.0 */ abstract class DatabaseImporter @@ -280,6 +283,31 @@ public function importData() } } + /** + * Check that a column type from an import file is a plain type declaration and not arbitrary SQL. + * + * Accepts a type name of one or more words, an optional length, precision or quoted value list in parentheses, + * optional modifiers such as "unsigned" and an optional array suffix. + * + * @param string $type The column type from the import file. + * + * @return string The type, if it is valid. + * + * @since __DEPLOY_VERSION__ + * @throws \RuntimeException if the type is not a plain type declaration. + */ + protected function checkColumnType(string $type): string + { + $quoted = "'(?:[^'\\\\]|''|\\\\.)*'"; + $values = '(?:[0-9, ]*|' . $quoted . '(?:\s*,\s*' . $quoted . ')*)'; + + if (!preg_match('/^[a-z][a-z0-9_ ]*(?:\(' . $values . '\))?[a-z ]*(?:\[\])?$/i', $type)) { + throw new \RuntimeException(sprintf('Invalid column type "%s" in the import file.', $type)); + } + + return $type; + } + /** * Merges the incoming structure definition with the existing structure. * @@ -317,10 +345,13 @@ public function mergeStructure() } } else { // This is a new table. + // Split on statement boundaries only, not on semicolons inside quoted defaults or comments $sql = $this->xmlToCreate($table); - $queries = explode(';', (string) $sql); + $queries = DatabaseDriver::splitSql((string) $sql); foreach ($queries as $query) { + $query = rtrim($query, "; \t\n\r"); + if (!empty($query)) { $this->db->setQuery((string) $query); $this->db->execute(); diff --git a/src/Mysql/MysqlImporter.php b/src/Mysql/MysqlImporter.php index 7c129747..564077ca 100644 --- a/src/Mysql/MysqlImporter.php +++ b/src/Mysql/MysqlImporter.php @@ -222,7 +222,7 @@ protected function getColumnSql(\SimpleXMLElement $field) $blobs = ['text', 'smalltext', 'mediumtext', 'largetext']; $fName = (string) $field['Field']; - $fType = (string) $field['Type']; + $fType = $this->checkColumnType((string) $field['Type']); $fNull = (string) $field['Null']; $fDefault = isset($field['Default']) ? (string) $field['Default'] : null; $fExtra = (string) $field['Extra']; @@ -250,6 +250,16 @@ protected function getColumnSql(\SimpleXMLElement $field) } if ($fExtra) { + // Only the attributes MySQL reports in the Extra column are allowed, not arbitrary SQL + if (!preg_match('/^(?:\s*(?:auto_increment|default_generated|invisible|on update current_timestamp(?:\(\d*\))?))+\s*$/i', $fExtra)) { + throw new \RuntimeException(sprintf('Invalid column attributes "%s" in the import file.', $fExtra)); + } + + // A generated default is an expression; only allow the current timestamp, quote anything else + if ($fDefault !== null && !preg_match('/^(?:current_timestamp(?:\(\d*\))?|now\(\))$/i', $fDefault)) { + $fDefault = $this->db->quote($fDefault); + } + // MySql 8.0 introduces DEFAULT_GENERATED in the extra column and should be replaced with the default value if (stristr($fExtra, 'DEFAULT_GENERATED') !== false) { $sql .= ' ' . strtoupper(str_ireplace('DEFAULT_GENERATED', 'DEFAULT ' . $fDefault, $fExtra)); @@ -349,7 +359,7 @@ protected function getKeySql($columns) $kLength = ''; if (!empty($column['Sub_part'])) { - $kLength = '(' . $column['Sub_part'] . ')'; + $kLength = '(' . (int) $column['Sub_part'] . ')'; } $kColumns[] = $this->db->quoteName((string) $column['Column_name']) . $kLength; diff --git a/src/Mysqli/MysqliImporter.php b/src/Mysqli/MysqliImporter.php index f6264d91..d4b548cf 100644 --- a/src/Mysqli/MysqliImporter.php +++ b/src/Mysqli/MysqliImporter.php @@ -258,7 +258,7 @@ protected function getColumnSql(\SimpleXMLElement $field) $blobs = ['text', 'smalltext', 'mediumtext', 'largetext']; $fName = (string) $field['Field']; - $fType = (string) $field['Type']; + $fType = $this->checkColumnType((string) $field['Type']); $fNull = (string) $field['Null']; $fDefault = isset($field['Default']) ? (string) $field['Default'] : null; $fExtra = (string) $field['Extra']; @@ -286,6 +286,16 @@ protected function getColumnSql(\SimpleXMLElement $field) } if ($fExtra) { + // Only the attributes MySQL reports in the Extra column are allowed, not arbitrary SQL + if (!preg_match('/^(?:\s*(?:auto_increment|default_generated|invisible|on update current_timestamp(?:\(\d*\))?))+\s*$/i', $fExtra)) { + throw new \RuntimeException(sprintf('Invalid column attributes "%s" in the import file.', $fExtra)); + } + + // A generated default is an expression; only allow the current timestamp, quote anything else + if ($fDefault !== null && !preg_match('/^(?:current_timestamp(?:\(\d*\))?|now\(\))$/i', $fDefault)) { + $fDefault = $this->db->quote($fDefault); + } + // MySql 8.0 introduces DEFAULT_GENERATED in the extra column and should be replaced with the default value if (stristr($fExtra, 'DEFAULT_GENERATED') !== false) { $sql .= ' ' . strtoupper(str_ireplace('DEFAULT_GENERATED', 'DEFAULT ' . $fDefault, $fExtra)); @@ -384,7 +394,7 @@ protected function getKeySql($columns) $kLength = ''; if (!empty($column['Sub_part'])) { - $kLength = '(' . $column['Sub_part'] . ')'; + $kLength = '(' . (int) $column['Sub_part'] . ')'; } $kColumns[] = $this->db->quoteName((string) $column['Column_name']) . $kLength; diff --git a/src/Pgsql/PgsqlImporter.php b/src/Pgsql/PgsqlImporter.php index 207c25d7..3489d8a0 100644 --- a/src/Pgsql/PgsqlImporter.php +++ b/src/Pgsql/PgsqlImporter.php @@ -321,7 +321,7 @@ protected function getAlterColumnSql($table, \SimpleXMLElement $field) $blobs = ['text', 'smalltext', 'mediumtext', 'largetext']; $fName = (string) $field['Field']; - $fType = (string) $field['Type']; + $fType = $this->checkColumnType((string) $field['Type']); $fNull = (string) $field['Null']; $fDefault = (isset($field['Default']) && $field['Default'] != 'NULL') ? @@ -368,11 +368,16 @@ protected function getAlterColumnSql($table, \SimpleXMLElement $field) protected function getColumnSql(\SimpleXMLElement $field) { $fName = (string) $field['Field']; - $fType = (string) $field['Type']; + $fType = $this->checkColumnType((string) $field['Type']); $fNull = (string) $field['Null']; if (strpos($field['Default'], '::') != false) { $fDefault = strstr($field['Default'], '::', true); + + // The part before the cast must be a plain literal or a sequence call, not arbitrary SQL + if (!preg_match("/^(?:'(?:[^']|'')*'|-?[0-9.]+|nextval\('(?:[^']|'')*')$/i", $fDefault)) { + $fDefault = $this->db->quote($fDefault); + } } else { $fDefault = isset($field['Default']) && strlen($field['Default']) > 0 ? preg_match('/^[0-9]$/', $field['Default']) ? $field['Default'] : $this->db->quote((string) $field['Default'])