Skip to content

Commit 421a9a4

Browse files
Copilotswissspidy
andcommitted
Remove assert calls and improve SQL string escaping for security
Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
1 parent 84b425f commit 421a9a4

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

src/DB_Users_Command.php

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,8 @@ public function create( $args, $assoc_args ) {
6666
// Escape identifiers for SQL
6767
$username_escaped = self::esc_sql_ident( $username );
6868
$host_escaped = self::esc_sql_ident( $host );
69-
assert( is_string( $username_escaped ) );
70-
assert( is_string( $host_escaped ) );
69+
/** @var string $username_escaped */
70+
/** @var string $host_escaped */
7171
$user_identifier = "{$username_escaped}@{$host_escaped}";
7272

7373
// Create user
@@ -84,7 +84,7 @@ public function create( $args, $assoc_args ) {
8484
if ( $grant_privileges ) {
8585
$database = DB_NAME;
8686
$database_escaped = self::esc_sql_ident( $database );
87-
assert( is_string( $database_escaped ) );
87+
/** @var string $database_escaped */
8888
$grant_query = "GRANT ALL PRIVILEGES ON {$database_escaped}.* TO {$user_identifier};";
8989
parent::run_query( $grant_query, $assoc_args );
9090

@@ -100,13 +100,19 @@ public function create( $args, $assoc_args ) {
100100
/**
101101
* Escapes a string for use in a SQL query.
102102
*
103+
* Follows MySQL's documented string literal escaping rules.
104+
* See https://dev.mysql.com/doc/refman/en/string-literals.html
105+
*
103106
* @param string $value String to escape.
104-
* @return string Escaped string.
107+
* @return string Escaped string, wrapped in single quotes.
105108
*/
106109
private function esc_sql_string( $value ) {
107-
// Escape backslashes first, then single quotes.
108-
$value = str_replace( '\\', '\\\\', $value );
109-
$value = str_replace( "'", "''", $value );
110+
// Escape special characters according to MySQL string literal rules.
111+
$value = str_replace(
112+
[ '\\', "\x00", "\n", "\r", "'", '"', "\x1a" ],
113+
[ '\\\\', "\\0", "\\n", "\\r", "\\'", '\\"', '\\Z' ],
114+
$value
115+
);
110116
return "'" . $value . "'";
111117
}
112118
}

0 commit comments

Comments
 (0)