Tag Archives: PHP

Turning On MySQL TLS for Sites I Don’t Control

I run a shared hosting platform with a lot of customer WordPress sites on it (thousands), and every one of them talks to a MySQL cluster over the network. I wanted that traffic encrypted and the server’s certificate verified, without editing a single customer site. PHP has no way to do that, so I wrote php-mysqlnd-tls, an extension that turns it on from php.ini:

mysqlnd_tls.enabled = On
mysqlnd_tls.hosts   = "db.example.com"

Only the Client Can Ask

In the MySQL protocol the server speaks first, and the client then decides whether to request TLS before it logs in. The server can accept a plaintext login or refuse it, but it can’t upgrade one.

The mysql command line client asks by default, but PHP doesn’t. On a stock PHP build, both mysqli and PDO connect through mysqlnd (for mysqli it’s been the only driver since PHP 8.2), and mysqlnd uses TLS only when the application requests it: MYSQLI_CLIENT_SSL, mysqli::ssl_set(), or the PDO::MYSQL_ATTR_SSL_* options. There’s no php.ini setting for it.

One Line per Site Is Still Too Many

WordPress can ask, with one line in wp-config.php:

define('MYSQL_CLIENT_FLAGS', MYSQLI_CLIENT_SSL);

That’s one edit per site, in a file the customer owns. Customers restore old backups, migrate sites in from other hosts, and reinstall from scratch, and each of those quietly puts the site back on plaintext. The line also does nothing for sites that aren’t WordPress.

Even where the line is set, WordPress passes the flag and nothing else, and with the flag alone mysqlnd doesn’t verify the server’s certificate. The connection is encrypted, but nothing checks who’s on the other end.

I could have added that line myself. PHP’s auto_prepend_file setting runs a file ahead of every script, so one prepended file could define the constant for every site. That means running my code inside every request to every customer’s site, which is a security issue. It’s a permissions issue too: the file has to be readable by each site’s own user and sit inside each site’s open_basedir, or PHP refuses to open it. And it’s still WordPress only.

The server side is no help. Set require_secure_transport = ON and MySQL refuses every plaintext login, which on day one means every site that hasn’t been edited. Requiring it user by user, with ALTER USER ... REQUIRE SSL, helps with a slow rollout, but it doesn’t solve the other issues: each of those sites still has to ask for TLS.

The Tunnel I Used Before

My old answer was a TLS tunnel that’s invisible to the sites: a proxy on each web server accepts plaintext MySQL connections and carries them inside TLS to the MySQL cluster, where a second proxy unwraps them.

The problem is that every database connection from every site goes through the tunnel, which makes it a single point of failure between two systems that were built to stay up. When it goes down, the web servers and MySQL are both still up, and every site shows a database error anyway.

MySQL also never sees TLS. The tunnel hands mysqld an ordinary plaintext TCP connection, so require_secure_transport and REQUIRE SSL can never be turned on.

Native TLS has neither problem: there’s nothing in between to fail, and both ends know the connection is encrypted, so the server can enforce it. I just needed a way to turn it on.

Moving the Decision to php.ini

mysqlnd has a plugin API that lets an extension replace the methods of its connection object. php-mysqlnd-tls replaces connect with a wrapper: for a host on the list it adds the TLS flag, sets the verification flags and the trust store, and calls the original. That’s about 250 lines of C. It never reads mysqlnd’s internal structures, which is why one source tree builds on every PHP version from 7.4 to 8.6.

For a host on the list, the setting decides what every site gets:

The site What it gets
Asks for nothing TLS, with the certificate and host name verified
Already asks for TLS (the WordPress define) The same; nothing conflicts
Sets its own CA, or asks for no verification The administrator’s trust store and verify setting
Sends a client certificate Kept, so accounts that require one keep working
Connects to a server that doesn’t offer TLS Refused. There’s no fallback to plaintext
Connects to any other host, or over a Unix socket Left exactly as it was

Only the Hosts You List

The policy applies to the hosts named in mysqlnd_tls.hosts and to nothing else. I list my own cluster, so every connection to it is encrypted and verified, whatever the site asked for.

A customer who connects to an external MySQL server is left alone. If their site asks for TLS, it gets TLS with its own settings, and if it connects in plaintext, that still works. It’s their server and their decision. The extension lets me enforce encryption on the servers I control without breaking a site that points somewhere else.

Rolling It Out

Every setting is PHP_INI_SYSTEM, so ini_set(), .htaccess, and .user.ini can’t change it. The administrator can still enable it per site, which makes it easy to roll out a few sites at a time:

<VirtualHost *:80>
    ServerName www.example.com
    php_admin_flag mysqlnd_tls.enabled on
</VirtualHost>

It installs with PIE. Each release carries pre-built binaries for PHP 7.4 through 8.6 on x86_64 and arm64, so most Linux servers don’t need a compiler:

pie install mikepultz/php-mysqlnd-tls

Then Enforce It on the Server

The extension makes PHP ask for TLS, but it can’t stop a client that doesn’t load it: anyone who can run php -n connects however they like, and so does anything that isn’t PHP. The session status shows what a connection actually got:

$row = $mysqli->query("show session status like 'Ssl_cipher'")->fetch_row();

echo ($row[1] === '') ? 'plaintext' : 'encrypted with ' . $row[1];

Once no client is still connecting in plaintext, set require_secure_transport = ON. That’s the setting I couldn’t touch at the start, and it’s on now.

The extension has been running in production for weeks now, and it works great.

Patching PHP’s Two Critical RCEs

On 21 October the PHP project released 8.5.12, 8.4.27, 8.3.36 and 8.2.35 to fix two remote code execution vulnerabilities, CVE-2026-109618 and CVE-2026-109619. Both are rated 9.2 on CVSS v4, and neither needs authentication. Both advisories say updating is the only complete fix.

Fixed Versions

Branch Fixed in
8.5 8.5.12
8.4 8.4.27
8.3 8.3.36
8.2 8.2.35
8.1 and older No upstream release. The PHP security team published minimal source backports for 7.4, 8.0 and 8.1; Debian and Ubuntu users can get fixed builds from packages.sury.org; otherwise check your LTS vendor.

Linux distributions received the patches in advance, so most systems get the fix as a normal package update.

The Two Bugs

CVE-2026-109618 is in out-of-memory handling. PHP aborts on an out-of-memory error with longjmp(). If that happens while it’s still parsing the request body, request data is left half-initialized, and request shutdown later processes it as valid. Crafted multipart requests can trigger this while staying inside PHP’s input limits. The fix removes longjmp() from out-of-memory handling.

CVE-2026-109619 is a use-after-free. A request that’s interrupted by a fatal error, a timeout or running out of memory can leave freed state behind on the worker, and a later request on the same worker can read it before initialization resets it. Confirmed paths include session upload progress, which is on by default and doesn’t need session_start(), and PHP 8.5’s fatal_error_backtraces. The impact includes memory disclosure as well as code execution.

Exposure by Server API

SAPI CVE-2026-109618 CVE-2026-109619
Apache mod_php Code execution validated with default limits, before application code runs Code execution confirmed
PHP-FPM Exploitable by source analysis, not fully demonstrated Code execution validated through session upload progress; depends on the application
php-cgi, FrankenPHP, LiteSpeed Listed as at risk by php.net

Checking What You Run

The CLI and the web server often run different PHP packages, so check the one serving requests:

php -v                      # CLI only
php-fpm -v                  # often versioned: php-fpm8.3 -v
apachectl -M | grep -i php  # is mod_php loaded?
apt policy php8.3-fpm       # Debian/Ubuntu: installed version and its repo

On Debian and Ubuntu, fixed builds reached packages.sury.org before the ppa:ondrej/php Launchpad PPA, so confirm the installed version if you use the PPA. Ondřej Surý is tracking the rollout, including the end-of-life branches, in this issue.

After updating, restart PHP-FPM or Apache so no worker is still running the old build. The full details, including interim settings for systems that can’t update immediately, are in the php.net advisory.

Climbing to PHPStan Level 10 on a Twelve-Year-Old Codebase

PHPStan has eleven rule levels, 0 through 10, and level 10 arrived with PHPStan 2.0. Running level 10 on a greenfield project is unremarkable. Running it on a codebase that started before PHP had scalar type hints is a different exercise, and the interesting part is where the return on effort falls off.

Start with a Baseline

The instinct is to run the tool, see thousands of errors, and start fixing. That stalls every time, because the work is unbounded and nothing improves until it is finished.

The baseline file inverts this. It records every existing error as accepted, so the reported count starts at zero and any error you add is yours:

vendor/bin/phpstan analyse --generate-baseline

From that point the tool is useful in CI immediately, on day one, at whatever level you eventually want to reach. New code is held to the standard and old code is a debt you pay down deliberately. The baseline shrinking over time is a much better signal than a number that started enormous and is still enormous.

The trap is letting the baseline get regenerated whenever it becomes inconvenient. Regenerating hides new errors along with old ones. Treat the file as append-only in practice, and make regenerating it a decision somebody has to justify in review.

What Each Level Actually Buys

The levels are not evenly spaced in either difficulty or value. On old code the distribution looked roughly like this for me.

Levels 0 through 5 are close to free and worth doing in one sitting. Unknown classes, unknown methods, wrong argument counts, obviously wrong argument types. These are real bugs in dead code paths, and they were the fastest defect-per-hour of the whole exercise.

Level 6 is the wall. It requires type hints everywhere, which on a legacy codebase means annotating thousands of parameters, properties, and returns that were never written down. It is also where the majority of the value is, because everything above it depends on the types being declared. Budget accordingly, and do it package by package rather than all at once.

Level 7 handles union types correctly, and level 8 reports calling methods on something that might be null. Level 8 found the largest number of genuine, user-visible bugs for me. Old PHP code is full of functions that return an object or false, and calling a method on the false path is a fatal error nobody had hit yet only because the input never went that way in production.

Level 9 treats explicit mixed strictly. Level 10 extends that to implicit mixed, meaning values that are untyped because nobody wrote a type rather than because someone chose mixed deliberately.

Where I Stopped, and Why

Nine was the point where the ratio turned. The errors at level 9 and above are overwhelmingly about proving to the analyser that something is what you already know it is, and the fix is usually an assertion or a narrowing check that exists for the tool rather than for the program.

That work is not worthless. Code paths handling data from outside the process, request parameters, decoded JSON, database rows, third-party API responses, are exactly where implicit mixed represents a real unverified assumption, and level 10 is right to flag them. Those are worth fixing properly.

Internal code where the types are obvious from three lines of context is a different story. There the analyser is asking you to restate something the reader can already see, and the resulting assertions add noise to every function. I run level 9 across the codebase and level 10 on the packages that parse external input, which PHPStan supports directly:

parameters:
    level: 9
    paths:
        - lib
        - bin
    ignoreErrors:
        - identifier: missingType.iterableValue
    tmpDir: build/phpstan

The missingType.iterableValue exclusion is the one I would flag as a genuine judgment call. Annotating every array with its value type via array<string, Thing> is real documentation and real safety, and on a large old codebase it is also an enormous amount of typing for arrays that get built and consumed twenty lines apart. Excluding it globally is a compromise. Excluding it only where the array does not cross a module boundary would be better and PHPStan cannot express that distinction.

The Part That Surprised Me

The bugs found were not the payoff. The payoff was that adding types forced decisions that had been deferred for years. A function returning Thing|false|null was not a typing problem, it was three different error conventions that had accumulated in one place, and writing the type down made that impossible to ignore.

Most of my level 6 work turned out to be design cleanup wearing a static analysis costume. That is a better argument for doing it than the defect count is.

PgBouncer, Prepared Statements, and Picking the Right Pool Mode

PgBouncer is the standard answer when an application opens more PostgreSQL connections than the server can usefully service. A process-per-request runtime and a serverless function that dials the database directly get there by completely different routes and land in the same place. The part that goes wrong is the pool mode, because the aggressive setting is the one everybody wants and it silently changes the semantics your code was written against.

Three Modes, One Real Decision

Session pooling assigns a server connection for the life of the client connection. It is safe and it buys you very little, since a worker process holding a connection for the length of a request is the situation you were trying to fix.

Transaction pooling assigns a server connection for the length of a transaction and returns it to the pool at commit. This is the mode that delivers the numbers people install PgBouncer for, and it is the mode with consequences.

Statement pooling returns the connection after every individual statement, which forbids multi-statement transactions entirely. It exists for specific workloads and is almost never what you want.

What Transaction Mode Takes Away

The rule is that anything living outside a transaction stops being reliable, because between two statements you may be on a different backend. That is a longer list than it first appears:

SET / RESET at session scope
LISTEN / NOTIFY
advisory locks taken outside a transaction
WITH HOLD cursors
temporary tables
session-scoped GUCs set by a connection hook

Session-level SET is the one that catches real applications. A framework bootstrap that sets search_path or timezone once on connect works perfectly in development against a direct connection, and in production the setting lands on whichever backend happened to serve that statement. Every later query gets a different backend without it. The failure is intermittent and nearly impossible to reproduce on demand.

Advisory locks are worse, because the failure is silent rather than noisy. A lock taken with pg_advisory_lock() outside a transaction belongs to a session you no longer control. The transaction-scoped variant, pg_advisory_xact_lock(), is released at commit and behaves correctly under transaction pooling. If you use advisory locks for job coordination, that one function name is the difference between working and quietly running the same job twice.

Prepared Statements Are Fixed, with Conditions

For years the answer to prepared statements under transaction pooling was that you could not use them. PgBouncer 1.21, released in October 2023, changed that. Set max_prepared_statements to a non-zero value and PgBouncer tracks named prepared statements itself, rewriting them to internal names and re-preparing them on whichever backend a client lands on:

[pgbouncer]
pool_mode = transaction
max_prepared_statements = 200

The value is the size of an LRU cache of statements kept on each server connection, so it wants to be at least as large as the number of distinct statements a typical request issues. Zero disables the feature and restores the old behavior.

The condition attached is important. This only works for protocol-level prepared statements, the ones sent through the extended query protocol. A literal PREPARE foo AS SELECT ... sent as a plain text query is invisible to PgBouncer and still breaks, because from the outside it is just another statement.

For PHP specifically, this means checking what PDO is actually doing. With ATTR_EMULATE_PREPARES left on, PDO interpolates parameters client-side and sends plain SQL, so there are no real prepared statements and nothing to break. Turn emulation off and you get genuine protocol-level prepares, which is what you want for both correctness and plan reuse, and which is exactly the case max_prepared_statements exists to handle.

$pdo = new PDO($dsn, $user, $pass, [
    PDO::ATTR_EMULATE_PREPARES => false,
    PDO::ATTR_ERRMODE          => PDO::ERRMODE_EXCEPTION,
]);

How I Choose

Start with transaction mode, then go looking for the session state your application depends on rather than waiting for it to surface. Grep for LISTEN, for pg_advisory_lock, for temporary tables, and for anything setting a GUC on connect. Move search_path out of a connection hook and into the connection string, where PgBouncer passes it through as part of the startup parameters and it survives correctly.

Keep a second pool in session mode on a different port for the small number of things that genuinely need a stable session, which is usually a migration runner and whatever handles LISTEN. Two pools with clear rules beats one pool with exceptions nobody remembers.

And size the pool against what PostgreSQL can actually do, since the point of pooling is to keep the database out of the region where it spends more time context switching than working. A pool larger than the database can service just moves the queue.

Net_DNS2 v2: Breaking a Decade of Backwards Compatibility

I have maintained Net_DNS2 since 2010. It started as a cleanup of the old PEAR Net_DNS library, and for most of its life the guiding rule was simple: do not break anyone. That rule held through PHP 5.3, 5.4, 7.x, and into 8.x. With v2.0 I broke it deliberately, and I think it was overdue.

What PEAR-Era Naming Costs You

Net_DNS2 predates PSR-4, namespaces, and any modern autoloading convention. The class naming reflected that:

$r = new Net_DNS2_Resolver(['nameservers' => ['8.8.8.8']]);
$result = $r->query('example.com', 'MX');

Underscores as a pseudo-namespace worked, and it left the library carrying an autoloader that mapped underscores to directory separators, class names that grew to Net_DNS2_RR_OPENPGPKEY, and no way to use any of the type machinery PHP had spent a decade adding. Every resource record type was a loosely typed bag of public properties. Every enumerated value was an integer or a bare string, validated by convention.

The practical cost was in the bug reports. A meaningful share were people passing the wrong type into something, getting no error, and finding out later when the wire format came out malformed. The library could not tell them, because it had no way to say what it expected.

v2.0 Requires PHP 8.1

The v2.0 rewrite moved to PSR-4 and real namespaces, with the parallel rename you would expect:

$r = new \NetDNS2\Resolver(['nameservers' => ['8.8.8.8']]);
$result = $r->query('example.com', 'MX');

The floor is PHP 8.1, which is what enums require. That version choice is the entire reason the break was worth making. DNS is a protocol built almost entirely out of small enumerated sets: record types, classes, opcodes, response codes, DNSSEC algorithms, digest types. Modelling those as integer constants means every function that accepts one accepts any integer. Modelling them as backed enums means the type system rejects nonsense before a packet is ever assembled.

Most class, method, and property names survived the move. Someone upgrading is mostly changing Net_DNS2_Thing to \NetDNS2\Thing and raising their PHP requirement, which is a mechanical change a search and replace handles. That was the design constraint I set for myself: break the naming, keep the shape.

Deciding to Break Compatibility

The argument against was straightforward. Net_DNS2 has a long tail of users on old PHP, often embedded in something they inherited and do not want to touch. A hard PHP 8.1 floor strands all of them.

What changed my mind was noticing that I was writing new code to work around the absence of types, then writing tests to catch the bugs that the absent types would have caught, then answering issues from people who hit those bugs anyway. The library was subsidising PHP 5 compatibility with permanent complexity, and the people paying that tax were mostly not the people benefiting from it.

The compromise is that v1.x still exists and still gets fixes. That is the part I would recommend to anyone in the same position. A hard break is much easier to justify when the old branch does not disappear the same day, and tagging a final v1 release that people can pin to costs almost nothing.

What I Would Do Differently

I would have done it sooner. The signal was there for years: every feature request that involved better validation ran into the same wall, and I kept routing around it. Deprecation cycles have a cost too, and carrying a compatibility promise you have quietly stopped believing in is worse than announcing the break.

I would also have been more aggressive about the enum conversion in one pass. Doing it incrementally meant a stretch where some values were enums and some were still integers, and the mixed state was more confusing than either endpoint. If you are going to break, break cleanly and finish.

If you use the library and are still on v1, there is no urgency. If you are starting something new on PHP 8.1 or later, start on v2. The DNS lookup tool on mrdns.com runs on this code, so it gets exercised against real-world responses continuously, which has caught more parsing edge cases than my test suite ever did.