Skip to content

Commit fb5c2e7

Browse files
committed
Add Opportunistic TLS implementation
This commit introduces the functionality required to build opportunistic TLS clients and servers with ReactPHP. It does so by introducing a prefix to `tls://`, namely `opportunistic`, to create `opportunistic+tls://example.com:5432` for example as the full URL. This will create an `OpportunisticTlsConnectionInterface` (instead of a `ConnectionInterface`) that extends the `ConnectionInterface` and exposes the `enableEncryption` method to enable TLS encryption at the desired moment. Inside this PR is an example of a server and client negotiating when to enable TLS and enable it when ready. Opportunistic Security described in RFC7435: https://www.rfc-editor.org/rfc/rfc7435 External PR using the proposed changes in this commit: voryx/PgAsync#52
1 parent 936546b commit fb5c2e7

11 files changed

+596
-12
lines changed

README.md

+111-4
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ handle multiple concurrent connections without blocking.
2323
* [ConnectionInterface](#connectioninterface)
2424
* [getRemoteAddress()](#getremoteaddress)
2525
* [getLocalAddress()](#getlocaladdress)
26+
* [OpportunisticTlsConnectionInterface](#opportunistictlsconnectioninterface)
27+
* [enableEncryption()](#enableencryption)
2628
* [Server usage](#server-usage)
2729
* [ServerInterface](#serverinterface)
2830
* [connection event](#connection-event)
@@ -193,6 +195,64 @@ If your system has multiple interfaces (e.g. a WAN and a LAN interface),
193195
you can use this method to find out which interface was actually
194196
used for this connection.
195197

198+
### OpportunisticTlsConnectionInterface
199+
200+
The `OpportunisticTlsConnectionInterface` extends the
201+
[`ConnectionInterface`](#connectioninterface) and adds the ability of
202+
enabling the TLS encryption on the connection when desired.
203+
204+
#### enableEncryption
205+
206+
When negotiated with the server when to start encrypting traffic using TLS, you
207+
can enable it by calling `enableEncryption()`. This will either return a promise
208+
that resolves with a `OpportunisticTlsConnectionInterface` connection or throw a
209+
`RuntimeException` if the encryption failed. If successful, all traffic back and
210+
forth will be encrypted. In the following example we ask the server if they want
211+
to encrypt the connection, and when it responds with `yes` we enable the encryption:
212+
213+
```php
214+
$connector = new React\Socket\Connector();
215+
$connector->connect('opportunistic+tls://example.com:5432/')->then(function (React\Socket\OpportunisticTlsConnectionInterface $startTlsConnection) {
216+
$connection->write('let\'s encrypt?');
217+
218+
return React\Promise\Stream\first($connection)->then(function ($data) use ($connection) {
219+
if ($data === 'yes') {
220+
return $connection->enableEncryption();
221+
}
222+
223+
return $stream;
224+
});
225+
})->then(function (React\Socket\ConnectionInterface $connection) {
226+
$connection->write('Hello!');
227+
});
228+
```
229+
230+
The `enableEncryption` function resolves with itself. As such you can't see the data
231+
encrypted when you hook into the events before enabling, as shown below:
232+
233+
```php
234+
$connector = new React\Socket\Connector();
235+
$connector->connect('opportunistic+tls://example.com:5432/')->then(function (React\Socket\OpportunisticTlsConnectionInterface $startTlsConnection) {
236+
$connection->on('data', function ($data) {
237+
echo 'Raw: ', $data, PHP_EOL;
238+
});
239+
240+
return $connection->enableEncryption();
241+
})->then(function (React\Socket\ConnectionInterface $connection) {
242+
$connection->on('data', function ($data) {
243+
echo 'TLS: ', $data, PHP_EOL;
244+
});
245+
});
246+
```
247+
248+
When the other side sends `Hello World!` over the encrypted connection, the output
249+
will be the following:
250+
251+
```
252+
Raw: Hello World!
253+
TLS: Hello World!
254+
```
255+
196256
## Server usage
197257

198258
### ServerInterface
@@ -253,10 +313,10 @@ If the address can not be determined or is unknown at this time (such as
253313
after the socket has been closed), it MAY return a `NULL` value instead.
254314

255315
Otherwise, it will return the full address (URI) as a string value, such
256-
as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443`
257-
`unix://example.sock` or `unix:///path/to/example.sock`.
258-
Note that individual URI components are application specific and depend
259-
on the underlying transport protocol.
316+
as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443`,
317+
`unix://example.sock`, `unix:///path/to/example.sock`, or
318+
`opportunistic+tls://127.0.0.1:443`. Note that individual URI components
319+
are application specific and depend on the underlying transport protocol.
260320

261321
If this is a TCP/IP based server and you only want the local port, you may
262322
use something like this:
@@ -478,6 +538,22 @@ $socket = new React\Socket\SocketServer('tls://127.0.0.1:8000', array(
478538
));
479539
```
480540

541+
To start a server with opportunistic TLS support use `opportunistic+tls://` as the scheme instead of `tls://`:
542+
543+
```php
544+
$socket = new React\Socket\SocketServer('opportunistic+tls://127.0.0.1:8000', array(
545+
'tls' => array(
546+
'local_cert' => 'server.pem',
547+
'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_SERVER
548+
)
549+
));
550+
$server->on('connection', static function (OpportunisticTlsConnectionInterface $connection) use ($server) {
551+
return $connection->enableEncryption();
552+
});
553+
```
554+
555+
See also the [examples](examples).
556+
481557
> Note that available [TLS context options](https://www.php.net/manual/en/context.ssl.php),
482558
their defaults and effects of changing these may vary depending on your system
483559
and/or PHP version.
@@ -697,6 +773,21 @@ here in order to use the [default loop](https://github.com/reactphp/event-loop#l
697773
This value SHOULD NOT be given unless you're sure you want to explicitly use a
698774
given event loop instance.
699775

776+
The `SecureServer` class supports opportunistic TLS by passing true in as a 4th
777+
constructor parameter. This, when a client connects, emits a
778+
[`OpportunisticTlsConnectionInterface`](#opportunistictlsconnectioninterface)
779+
instead of the default [`ConnectionInterface`](#connectioninterface). It won't be
780+
TLS encrypted from the start, but you can enable the TLS encryption on the connection
781+
after negotiating with the client.
782+
783+
```php
784+
$server = new React\Socket\TcpServer(8000);
785+
$server = new React\Socket\SecureServer($server, null, array(
786+
'local_cert' => 'server.pem',
787+
'passphrase' => 'secret'
788+
), true);
789+
```
790+
700791
> Advanced usage: Despite allowing any `ServerInterface` as first parameter,
701792
you SHOULD pass a `TcpServer` instance as first parameter, unless you
702793
know what you're doing.
@@ -1389,6 +1480,22 @@ $secureConnector = new React\Socket\SecureConnector($dnsConnector, null, array(
13891480
));
13901481
```
13911482

1483+
The `SecureConnector` class supports opportunistic TLS by using
1484+
`opportunistic-tls://` as scheme instead of `tls://`. This, when connected,
1485+
returns a [`OpportunisticTlsConnectionInterface`](#opportunistictlsconnectioninterface)
1486+
instead of the default [`ConnectionInterface`](#connectioninterface). It won't be
1487+
TLS encrypted from the start, but you can enable the TLS encryption on the connection
1488+
after negotiating with the server.
1489+
1490+
```php
1491+
$secureConnector = new React\Socket\SecureConnector($dnsConnector);
1492+
$secureConnector->connect('opportunistic-tls://example.com:5432')->then(function (OpportunisticTlsConnectionInterface $connection) {
1493+
return $connection->enableEncryption();
1494+
})->then(function (OpportunisticTlsConnectionInterface $connection) {
1495+
$connection->write('Encrypted hi!');
1496+
});
1497+
```
1498+
13921499
> Advanced usage: Internally, the `SecureConnector` relies on setting up the
13931500
required *context options* on the underlying stream resource.
13941501
It should therefor be used with a `TcpConnector` somewhere in the connector

examples/31-opportunistic-tls.php

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
<?php
2+
3+
// Opportunistic TLS example showing a basic negotiation before enabling the encryption. It starts out as an
4+
// unencrypted TCP connection. After both parties agreed to encrypt the connection they both enable the encryption.
5+
// After which any communication over the line is encrypted.
6+
//
7+
// This example is design to show both sides in one go, as such the server stops listening for new connection after
8+
// the first, this makes sure the loop shuts down after the example connection has closed.
9+
//
10+
// $ php examples/31-opportunistic-tls.php
11+
12+
use React\EventLoop\Loop;
13+
use React\Socket\ConnectionInterface;
14+
use React\Socket\Connector;
15+
use React\Socket\OpportunisticTlsConnectionInterface;
16+
use React\Socket\SocketServer;
17+
18+
require __DIR__ . '/../vendor/autoload.php';
19+
20+
$server = new SocketServer('opportunistic+tls://127.0.0.1:0', array(
21+
'tls' => array(
22+
'local_cert' => __DIR__ . '/localhost.pem',
23+
)
24+
));
25+
$server->on('connection', static function (OpportunisticTlsConnectionInterface $connection) use ($server) {
26+
$server->close();
27+
28+
$connection->on('data', function ($data) {
29+
echo 'From Client: ', $data, PHP_EOL;
30+
});
31+
React\Promise\Stream\first($connection)->then(function ($data) use ($connection) {
32+
if ($data === 'Let\'s encrypt?') {
33+
$connection->write('yes');
34+
return $connection->enableEncryption();
35+
}
36+
37+
return $connection;
38+
})->then(static function (ConnectionInterface $connection) {
39+
$connection->write('Encryption enabled!');
40+
})->done();
41+
});
42+
43+
$client = new Connector(array(
44+
'tls' => array(
45+
'verify_peer' => false,
46+
'verify_peer_name' => false,
47+
'allow_self_signed' => true,
48+
),
49+
));
50+
$client->connect($server->getAddress())->then(static function (OpportunisticTlsConnectionInterface $connection) {
51+
$connection->on('data', function ($data) {
52+
echo 'From Server: ', $data, PHP_EOL;
53+
});
54+
$connection->write('Let\'s encrypt?');
55+
56+
return React\Promise\Stream\first($connection)->then(function ($data) use ($connection) {
57+
if ($data === 'yes') {
58+
return $connection->enableEncryption();
59+
}
60+
61+
return $connection;
62+
});
63+
})->then(function (ConnectionInterface $connection) {
64+
$connection->write('Encryption enabled!');
65+
Loop::addTimer(1, static function () use ($connection) {
66+
$connection->end('Cool! Bye!');
67+
});
68+
})->done();

src/Connector.php

+4
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ public function __construct($context = array(), $loop = null)
7575
'dns' => true,
7676
'timeout' => true,
7777
'happy_eyeballs' => true,
78+
'opportunistic+tls' => true,
7879
);
7980

8081
if ($context['timeout'] === true) {
@@ -150,6 +151,9 @@ public function __construct($context = array(), $loop = null)
150151
}
151152

152153
$this->connectors['tls'] = $context['tls'];
154+
if ($context['opportunistic+tls'] !== false) {
155+
$this->connectors['opportunistic+tls'] = $this->connectors['tls'];
156+
}
153157
}
154158

155159
if ($context['unix'] !== false) {

src/OpportunisticTlsConnection.php

+109
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
<?php
2+
3+
namespace React\Socket;
4+
5+
use Evenement\EventEmitter;
6+
use React\EventLoop\LoopInterface;
7+
use React\Promise\PromiseInterface;
8+
use React\Stream\DuplexResourceStream;
9+
use React\Stream\Util;
10+
use React\Stream\WritableResourceStream;
11+
use React\Stream\WritableStreamInterface;
12+
13+
/**
14+
* The actual connection implementation for StartTlsConnectionInterface
15+
*
16+
* This class should only be used internally, see StartTlsConnectionInterface instead.
17+
*
18+
* @see OpportunisticTlsConnectionInterface
19+
* @internal
20+
*/
21+
class OpportunisticTlsConnection extends EventEmitter implements OpportunisticTlsConnectionInterface
22+
{
23+
/** @var Connection */
24+
private $connection;
25+
26+
/** @var StreamEncryption */
27+
private $streamEncryption;
28+
29+
/** @var string */
30+
private $uri;
31+
32+
public function __construct(Connection $connection, StreamEncryption $streamEncryption, $uri)
33+
{
34+
$this->connection = $connection;
35+
$this->streamEncryption = $streamEncryption;
36+
$this->uri = $uri;
37+
38+
Util::forwardEvents($connection, $this, array('data', 'end', 'error', 'close'));
39+
}
40+
41+
public function getRemoteAddress()
42+
{
43+
return $this->connection->getRemoteAddress();
44+
}
45+
46+
public function getLocalAddress()
47+
{
48+
return $this->connection->getLocalAddress();
49+
}
50+
51+
public function isReadable()
52+
{
53+
return $this->connection->isReadable();
54+
}
55+
56+
public function pause()
57+
{
58+
$this->connection->pause();
59+
}
60+
61+
public function resume()
62+
{
63+
$this->connection->resume();
64+
}
65+
66+
public function pipe(WritableStreamInterface $dest, array $options = array())
67+
{
68+
return $this->connection->pipe($dest, $options);
69+
}
70+
71+
public function close()
72+
{
73+
$this->connection->close();
74+
}
75+
76+
public function enableEncryption()
77+
{
78+
$that = $this;
79+
$connection = $this->connection;
80+
$uri = $this->uri;
81+
82+
return $this->streamEncryption->enable($connection)->then(function () use ($that) {
83+
return $that;
84+
}, function ($error) use ($connection, $uri) {
85+
// establishing encryption failed => close invalid connection and return error
86+
$connection->close();
87+
88+
throw new \RuntimeException(
89+
'Connection to ' . $uri . ' failed during TLS handshake: ' . $error->getMessage(),
90+
$error->getCode()
91+
);
92+
});
93+
}
94+
95+
public function isWritable()
96+
{
97+
return $this->connection->isWritable();
98+
}
99+
100+
public function write($data)
101+
{
102+
return $this->connection->write($data);
103+
}
104+
105+
public function end($data = null)
106+
{
107+
$this->connection->end($data);
108+
}
109+
}

0 commit comments

Comments
 (0)