Skip to content

Commit 70bdaf3

Browse files
authored
Require MySQL proxy authentication and default to loopback (#540)
## Summary The experimental MySQL proxy currently accepts arbitrary credentials and listens on all network interfaces. This PR **requires authentication before database access** and **binds to `127.0.0.1` by default**. It also adds connection limits, timeouts, and safer packet handling so that malformed requests and clients that stop reading do not disrupt other connections. ## What changes The changes cover authentication, connection handling, and error reporting: - **Account authentication.** Credentials are checked before any SQL runs, including the initial database selection. Accounts use `caching_sha2_password` by default, with `mysql_native_password` available for older clients. Clients are asked to switch to the account's configured method when needed. - **Configurable listener and password sources.** The CLI and PHP API accept IPv4 or IPv6 bind addresses. CLI passwords come from `WP_MYSQL_PROXY_PASSWORD` or a password file, including a pipe such as `/dev/stdin`. Invalid or incomplete CLI options are rejected. - **Connection cleanup and timeouts.** Failed logins close the connection and discard queued commands. Clients that stop reading cannot block other connections, and `COM_QUIT` closes the connection without a response. - **Safer request processing.** Split packets are joined before a query runs. Oversized messages and empty command packets are rejected. Database names in `COM_INIT_DB` are quoted, and failed selections return MySQL's unknown-database error. - **Error reporting and logging.** Client requests and response data are excluded from debug logs. Internal errors are logged with their source location, while clients receive `1105 Unknown error`. Query errors retain their useful messages. ### Connection and request limits Connection counts and timeouts follow MySQL's defaults. Login packets are capped at 16 KB, and complete messages at the MySQL client default of 16 MB. | Limit | Value | | --- | --- | | Open connections | 151 | | Login or authentication-switch response | 10 seconds | | Idle connection | 8 hours | | No progress while sending a request | 30 seconds | | No progress while accepting a response | 60 seconds | Regression coverage includes malformed and fragmented logins, replay attempts, queued commands, credential logging, stalled clients, and connections through the MySQL CLI, PDO, and MySQLi. CI runs the proxy suite on PHP 7.2 and 8.5. ## Compatibility Existing callers need the following updates: - **Supply credentials.** CLI callers must provide `--user` and a password source. PHP callers must pass a `MySQL_Authentication` account through the `authentication` option of `MySQL_Proxy`, or as the third argument of `MySQL_Session`. - **Choose native authentication for clients that require it.** PDO and MySQLi on PHP below 7.4.4, and clients such as Node's `mysql` package, need `mysql_native_password`. Set `--auth-plugin=mysql_native_password`, or pass it as the third `MySQL_Authentication` argument. - **Set the bind address for remote access.** The default listener accepts only local connections. - **Use `-P` for the CLI port.** This matches MySQL clients; `-p` is no longer accepted. There are also two changes for direct API users: - **Catch internal adapter errors.** `SQLite_Adapter::handle_query()` now throws internal errors and returns error results only for query errors. `MySQL_Session` handles these exceptions for proxy callers. - **Handle malformed protocol input.** `read_length_encoded_int()`, `read_length_encoded_string()`, and `read_null_terminated_string()` now throw `MySQL_Proxy_Exception` for invalid or truncated input. **TLS remains unsupported.** Authentication does not encrypt queries or results. Remote connections need a protected transport, such as an SSH tunnel. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit - **New Features** - Added username and password authentication with caching SHA-2 and native-password support. - Added password-file and environment-variable credential options. - Added configurable IPv4 and IPv6 listener addresses, defaulting to loopback. - Added connection limits and timeouts, with improved handling of slow clients. - **Bug Fixes** - Improved handling of malformed, incomplete, oversized, and fragmented MySQL packets. - Kept credentials and internal error details out of logs and client responses. - Corrected default last-insert-ID behavior. - **Documentation** - Updated CLI and PHP guidance with credential requirements, authentication options, defaults, and network exposure details. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 84bff0c commit 70bdaf3

26 files changed

Lines changed: 3121 additions & 316 deletions

‎.github/workflows/mysql-proxy-tests.yml‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,13 @@ permissions: {}
1212

1313
jobs:
1414
test:
15-
name: MySQL Proxy Tests
15+
name: MySQL Proxy Tests (PHP ${{ matrix.php }})
1616
runs-on: ubuntu-latest
1717
timeout-minutes: 20
18+
strategy:
19+
fail-fast: false
20+
matrix:
21+
php: ['7.2', '8.5']
1822
permissions:
1923
contents: read # Required to clone the repo.
2024

@@ -25,7 +29,8 @@ jobs:
2529
- name: Set up PHP
2630
uses: shivammathur/setup-php@v2
2731
with:
28-
php-version: '7.2'
32+
php-version: ${{ matrix.php }}
33+
extensions: sockets, pdo_mysql, pdo_sqlite, mysqli
2934
coverage: none
3035

3136
- name: Configure monorepo package repository

‎packages/mysql-proxy/README.md‎

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,32 +32,60 @@ composer require wordpress/mysql-proxy wordpress/mysql-on-sqlite:^3.0
3232
### CLI:
3333

3434
```bash
35-
$ ./vendor/bin/wp-mysql-proxy.php [--port <port>] [--database <path/to/db.sqlite>] [--log-level <log_level>]
35+
$ ./vendor/bin/wp-mysql-proxy.php --user <username> [--password-file <path>] [--bind-address <address>] [--auth-plugin <name>] [--port <port>] [--database <path/to/db.sqlite>] [--log-level <log_level>]
3636

3737
Options:
3838
-h, --help Show this help message and exit.
39-
-p, --port=<port> The port to listen on. Default: 3306
39+
-u, --user=<username> The proxy account name. Required.
40+
--password-file=<path> Read the password from a file instead of WP_MYSQL_PROXY_PASSWORD.
41+
--bind-address=<ip> The IPv4 or IPv6 address to listen on. Default: 127.0.0.1
42+
--auth-plugin=<name> The account's authentication plugin, either
43+
caching_sha2_password or mysql_native_password.
44+
Use the latter only for clients that need it.
45+
Default: caching_sha2_password
46+
-P, --port=<port> The port to listen on. Default: 3306
4047
-d, --database=<path> The path to the SQLite database file. Default: :memory:
4148
-l, --log-level=<level> The log level to use. One of 'error', 'warning', 'info', 'debug'. Default: info
49+
50+
A nonempty password is required via WP_MYSQL_PROXY_PASSWORD or --password-file.
51+
Password files are read verbatim, including any trailing newline.
52+
Connections are not encrypted (no TLS). For remote clients, use an SSH tunnel.
4253
```
4354
4455
When working from a checked-out repository, Composer does not create a proxy for
4556
the root package's own binary. Run it directly from the package directory:
4657

4758
```bash
48-
php bin/wp-mysql-proxy.php [--port <port>] [--database <path/to/db.sqlite>] [--log-level <log_level>]
59+
php bin/wp-mysql-proxy.php --user <username> [--password-file <path>] [--bind-address <address>] [--auth-plugin <name>] [--port <port>] [--database <path/to/db.sqlite>] [--log-level <log_level>]
4960
```
5061

5162
### PHP:
5263
```php
64+
use WP_MySQL_Proxy\MySQL_Authentication;
5365
use WP_MySQL_Proxy\MySQL_Proxy;
5466
use WP_MySQL_Proxy\Adapter\SQLite_Adapter;
5567
5668
require_once __DIR__ . '/vendor/autoload.php';
5769
5870
$proxy = new MySQL_Proxy(
5971
new SQLite_Adapter( $db_path ),
60-
array( 'port' => $port, 'log_level' => $log_level )
72+
array(
73+
'authentication' => new MySQL_Authentication( 'proxy', getenv( 'WP_MYSQL_PROXY_PASSWORD' ) ),
74+
'port' => $port,
75+
'log_level' => $log_level,
76+
)
6177
);
6278
$proxy->start();
6379
```
80+
81+
The account uses `caching_sha2_password` by default, which PDO and MySQLi on PHP
82+
below 7.4.4 can't use. For those clients, set `--auth-plugin=mysql_native_password`,
83+
or pass `mysql_native_password` as the third `MySQL_Authentication` argument.
84+
85+
The proxy listens on `127.0.0.1` by default. Set `--bind-address` (or the PHP
86+
`bind_address` option) to an IPv4 or IPv6 address to change the listener. Binding
87+
to `0.0.0.0` or `::` explicitly exposes the proxy on all interfaces.
88+
89+
The proxy doesn't support TLS. Queries, results, and logins travel unencrypted,
90+
and anyone who records a login can try to guess the password offline. For remote
91+
clients, keep the default address and connect through an SSH tunnel.
Lines changed: 128 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,163 @@
11
<?php declare( strict_types = 1 );
22

3+
use WP_MySQL_Proxy\MySQL_Authentication;
4+
use WP_MySQL_Proxy\MySQL_Protocol;
35
use WP_MySQL_Proxy\MySQL_Proxy;
46
use WP_MySQL_Proxy\Adapter\SQLite_Adapter;
57
use WP_MySQL_Proxy\Logger;
68

79
require_once $_composer_autoload_path ?? __DIR__ . '/../vendor/autoload.php';
810

9-
// Process CLI arguments:
10-
$shortopts = 'hd:p:l:';
11-
$longopts = array( 'help', 'database:', 'port:', 'log-level:' );
12-
$opts = getopt( $shortopts, $longopts );
11+
// Parse every argument: getopt() silently discards unknown or incomplete options.
12+
$aliases = array(
13+
'h' => 'help',
14+
'd' => 'database',
15+
'P' => 'port',
16+
'l' => 'log-level',
17+
'u' => 'user',
18+
);
19+
$options = array( 'help', 'database', 'port', 'log-level', 'bind-address', 'user', 'password-file', 'auth-plugin' );
20+
$args = array_slice( $argv, 1 );
21+
$opts = array();
22+
23+
// Never include argument values in errors: an unknown option may contain a password.
24+
$option_error = "Error: Invalid command-line options. Use --help for supported options and required values.\n";
25+
26+
for ( $i = 0; $i < count( $args ); $i++ ) {
27+
$arg = $args[ $i ];
28+
$name = '';
29+
$value = null;
30+
if ( 0 === strpos( $arg, '--' ) ) {
31+
$parts = explode( '=', substr( $arg, 2 ), 2 );
32+
$name = $parts[0];
33+
$value = $parts[1] ?? null;
34+
} elseif ( '-' === substr( $arg, 0, 1 ) && strlen( $arg ) > 1 ) {
35+
$name = $aliases[ $arg[1] ] ?? '';
36+
if ( strlen( $arg ) > 2 ) {
37+
if ( 'help' === $name ) {
38+
array_splice( $args, $i + 1, 0, array( '-' . substr( $arg, 2 ) ) );
39+
} else {
40+
$value = substr( $arg, 2 );
41+
}
42+
}
43+
}
44+
45+
if ( ! in_array( $name, $options, true ) || array_key_exists( $name, $opts )
46+
|| ( 'help' === $name && null !== $value )
47+
) {
48+
fwrite( STDERR, $option_error );
49+
exit( 1 );
50+
}
51+
if ( 'help' === $name ) {
52+
$opts[ $name ] = true;
53+
continue;
54+
}
55+
// A separate value can't look like an option, so a missing value isn't
56+
// filled with the next option. Use --option=-value for such a value.
57+
if ( null === $value && isset( $args[ $i + 1 ] ) && 0 !== strpos( $args[ $i + 1 ], '-' ) ) {
58+
$value = $args[ ++$i ];
59+
}
60+
if ( null === $value ) {
61+
fwrite( STDERR, $option_error );
62+
exit( 1 );
63+
}
64+
$opts[ $name ] = $value;
65+
}
1366

1467
$help = <<<USAGE
15-
Usage: wp-mysql-proxy.php [--port <port>] [--database <path/to/db.sqlite>] [--log-level <log_level>]
68+
Usage: wp-mysql-proxy.php --user <username> [--password-file <path>] [--bind-address <address>] [--auth-plugin <name>] [--port <port>] [--database <path/to/db.sqlite>] [--log-level <log_level>]
1669
1770
Options:
1871
-h, --help Show this help message and exit.
19-
-p, --port=<port> The port to listen on. Default: 3306
72+
-u, --user=<username> The proxy account name. Required.
73+
--password-file=<path> Read the password from a file instead of WP_MYSQL_PROXY_PASSWORD.
74+
--bind-address=<ip> The IPv4 or IPv6 address to listen on. Default: 127.0.0.1
75+
--auth-plugin=<name> The account's authentication plugin, either
76+
caching_sha2_password or mysql_native_password.
77+
Use the latter only for clients that need it.
78+
Default: caching_sha2_password
79+
-P, --port=<port> The port to listen on. Default: 3306
2080
-d, --database=<path> The path to the SQLite database file. Default: :memory:
2181
-l, --log-level=<level> The log level to use. One of 'error', 'warning', 'info', 'debug'. Default: info
2282
83+
A nonempty password is required via WP_MYSQL_PROXY_PASSWORD or --password-file.
84+
Password files are read verbatim, including any trailing newline.
85+
Connections are not encrypted (no TLS). For remote clients, use an SSH tunnel.
86+
2387
USAGE;
2488

2589
// Help.
26-
if ( isset( $opts['h'] ) || isset( $opts['help'] ) ) {
90+
if ( isset( $opts['help'] ) ) {
2791
fwrite( STDERR, $help );
2892
exit( 0 );
2993
}
3094

3195
// Database path.
32-
$db_path = $opts['d'] ?? $opts['database'] ?? ':memory:';
96+
$db_path = $opts['database'] ?? ':memory:';
97+
98+
// Validate options before SQLite_Adapter opens or creates the database file.
99+
// MySQL_Proxy checks the bind address too, but only after that.
100+
101+
// Bind address.
102+
$bind_address = $opts['bind-address'] ?? '127.0.0.1';
103+
if ( false === filter_var( $bind_address, FILTER_VALIDATE_IP ) ) {
104+
fwrite( STDERR, "Error: --bind-address must be a valid IPv4 or IPv6 address.\n" );
105+
exit( 1 );
106+
}
33107

34108
// Port.
35-
$port = (int) ( $opts['p'] ?? $opts['port'] ?? 3306 );
36-
if ( $port < 1 || $port > 65535 ) {
109+
$port = filter_var( $opts['port'] ?? 3306, FILTER_VALIDATE_INT );
110+
if ( false === $port || $port < 1 || $port > 65535 ) {
37111
fwrite( STDERR, "Error: --port must be an integer between 1 and 65535. Use --help for more information.\n" );
38112
exit( 1 );
39113
}
40114

41115
// Log level.
42-
$log_level = $opts['l'] ?? $opts['log-level'] ?? 'info';
116+
$log_level = $opts['log-level'] ?? 'info';
43117
if ( ! in_array( $log_level, Logger::LEVELS, true ) ) {
44118
fwrite( STDERR, 'Error: --log-level must be one of: ' . implode( ', ', Logger::LEVELS ) . ". Use --help for more information.\n" );
45119
exit( 1 );
46120
}
47121

122+
// Account. Do not accept passwords as command-line arguments.
123+
$password = getenv( 'WP_MYSQL_PROXY_PASSWORD' );
124+
if ( isset( $opts['password-file'] ) ) {
125+
$password_file = $opts['password-file'];
126+
127+
// Pipes, such as /dev/stdin or a process substitution, keep the password off the disk.
128+
if ( ! is_readable( $password_file ) || is_dir( $password_file ) ) {
129+
fwrite( STDERR, "Error: --password-file must name a readable file.\n" );
130+
exit( 1 );
131+
}
132+
133+
// On Linux, PHP can't open a pipe by its /dev/fd path, so read a descriptor of
134+
// this process through php://fd. See https://github.com/php/php-src/issues/9551.
135+
$source = $password_file;
136+
if ( '/dev/stdin' === $password_file ) {
137+
$source = 'php://fd/0';
138+
} elseif ( preg_match( '~^/(?:dev|proc/self)/fd/(\d+)$~', $password_file, $match ) ) {
139+
$source = 'php://fd/' . $match[1];
140+
}
141+
142+
// Report a failed read without PHP's warning, which names the path.
143+
$password = @file_get_contents( $source ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
144+
if ( false === $password ) {
145+
fwrite( STDERR, "Error: --password-file could not be read.\n" );
146+
exit( 1 );
147+
}
148+
}
149+
try {
150+
$authentication = new MySQL_Authentication(
151+
$opts['user'] ?? '',
152+
(string) $password,
153+
$opts['auth-plugin'] ?? MySQL_Protocol::DEFAULT_AUTH_PLUGIN
154+
);
155+
} catch ( InvalidArgumentException $e ) {
156+
fwrite( STDERR, 'Error: ' . $e->getMessage() . " Use --help for more information.\n" );
157+
exit( 1 );
158+
}
159+
unset( $password );
160+
48161
if ( ! class_exists( 'WP_MySQL_On_SQLite' ) ) {
49162
fwrite(
50163
STDERR,
@@ -57,8 +170,10 @@
57170
$proxy = new MySQL_Proxy(
58171
new SQLite_Adapter( $db_path ),
59172
array(
60-
'port' => $port,
61-
'log_level' => $log_level,
173+
'authentication' => $authentication,
174+
'bind_address' => $bind_address,
175+
'port' => $port,
176+
'log_level' => $log_level,
62177
)
63178
);
64179
$proxy->start();

‎packages/mysql-proxy/composer.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
},
1818
"require": {
1919
"php": ">=7.2",
20+
"ext-filter": "*",
21+
"ext-hash": "*",
2022
"ext-sockets": "*",
2123
"composer-runtime-api": "^2.2"
2224
},
@@ -33,6 +35,8 @@
3335
"bin/wp-mysql-proxy.php"
3436
],
3537
"require-dev": {
38+
"ext-mysqli": "*",
39+
"ext-pdo_mysql": "*",
3640
"phpunit/phpunit": "^8.5",
3741
"symfony/process": "^5.4",
3842
"wordpress/mysql-on-sqlite": "*@dev"

‎packages/mysql-proxy/src/Adapter/class-sqlite-adapter.php‎

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22

33
namespace WP_MySQL_Proxy\Adapter;
44

5+
use Error;
56
use PDO;
67
use PDOException;
78
use PDOStatement;
8-
use Throwable;
99
use WP_MySQL_Proxy\MySQL_Result;
1010
use WP_MySQL_On_SQLite;
1111
use WP_MySQL_Proxy\MySQL_Protocol;
@@ -23,7 +23,7 @@ public function __construct( $sqlite_database_path ) {
2323

2424
public function handle_query( string $query ): MySQL_Result {
2525
$affected_rows = 0;
26-
$last_insert_id = null;
26+
$last_insert_id = 0;
2727
$columns = array();
2828
$rows = array();
2929

@@ -39,12 +39,13 @@ public function handle_query( string $query ): MySQL_Result {
3939
$columns = $this->computeColumnInfo( $statement );
4040
}
4141
return MySQL_Result::from_data( $affected_rows, $last_insert_id, $columns, $rows ?? array() );
42-
} catch ( Throwable $e ) {
43-
$error_info = $e->errorInfo ?? null; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
44-
if ( $e instanceof PDOException && $error_info ) {
45-
return MySQL_Result::from_error( $error_info[0], $error_info[1], $error_info[2] );
42+
} catch ( PDOException $e ) {
43+
// Only query errors reach the client. The session logs internal errors instead.
44+
$error_info = $e->errorInfo; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
45+
if ( ! $error_info || $this->is_internal_error( $e ) ) {
46+
throw $e;
4647
}
47-
return MySQL_Result::from_error( 'HY000', 1105, $e->getMessage() ?? 'Unknown error' );
48+
return MySQL_Result::from_error( $error_info[0], $error_info[1], $error_info[2] );
4849
}
4950
}
5051

@@ -101,4 +102,22 @@ public function computeColumnInfo( PDOStatement $statement ) {
101102
}
102103
return $columns;
103104
}
105+
106+
/**
107+
* Whether a query exception is a PHP error that the driver reported as a query error.
108+
*
109+
* A PHP error is a bug, not a query error, and its message can contain server
110+
* file paths.
111+
*
112+
* @param PDOException $e The query exception.
113+
* @return bool
114+
*/
115+
private function is_internal_error( PDOException $e ): bool {
116+
for ( $cause = $e->getPrevious(); null !== $cause; $cause = $cause->getPrevious() ) {
117+
if ( $cause instanceof Error ) {
118+
return true;
119+
}
120+
}
121+
return false;
122+
}
104123
}

0 commit comments

Comments
 (0)