phpsslphp-stream-wrappers

Force minimum TLS version for stream connections


I'm looking to force a minimum version of TLS 1.2 for my client connection. I can do something like this:

$client = stream_socket_client('tlsv1.2://www.example.com:443');

This wrapper forces a TLS 1.2 connection. But doesn't allow for upgrades to 1.3 when the server is capable, and doesn't connect at all if the server only offers 1.3. There don't seem to be any options for stream_context_create() to affect the TLS version, and I don't want to use the curl extension. Is there any possibility to do this?


Solution

  • Another option to limit the protocol used (without the other restrictions implemented by setting security_level) is an undocumented option that can be passed to stream_context_create() called min_proto_version. Found it in the source, and confirmed it's available since PHP 8.0 at least.

    So the code becomes:

    $ctx = stream_context_create([
        'ssl' => ['min_proto_version' => STREAM_CRYPTO_PROTO_TLSv1_2]
    ]);
    $client = stream_socket_client('tls://www.example.com:443', context: $ctx);
    

    There is also an accompanying max_proto_version option as well.