Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions Tests/Mysqli/MysqliImporterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
[
'<field Field="a" Type="int; DROP TABLE x" Null="YES" Key="" Extra="" />',
'<field Field="a" Type="int" Null="YES" Key="" Extra="auto_increment; DROP TABLE x" />',
] 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('<field Field="a" Type="enum(' . "'x','y'" . ')" Null="NO" Key="" Default="x" Extra="" />')),
'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 = '<mysqldump><database name=""><table_structure name="#__semi">'
. '<field Field="a" Type="varchar(10)" Null="NO" Key="" Default="x;y" Extra="" />'
. '</table_structure></database></mysqldump>';

$importer = new MysqliImporter();
$importer->setDbo($db)->from($xml)->asXml()->mergeStructure();

$this->assertCount(1, $queries);
$this->assertStringContainsString("DEFAULT 'x;y'", $queries[0]);
}
}

33 changes: 32 additions & 1 deletion src/DatabaseImporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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();
Expand Down
14 changes: 12 additions & 2 deletions src/Mysql/MysqlImporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'];
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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;
Expand Down
14 changes: 12 additions & 2 deletions src/Mysqli/MysqliImporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'];
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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;
Expand Down
9 changes: 7 additions & 2 deletions src/Pgsql/PgsqlImporter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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') ?
Expand Down Expand Up @@ -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'])
Expand Down
Loading