Transport Encryption - SSL/TLS
Q:
How to ensure secure communication with Workerman?
A:
A convenient approach is to add an SSL encryption layer on top of the communication protocol, such as the wss or https protocols, which are both based on SSL encrypted transmission and are very secure. Workerman itself supports SSL (requires Workerman>=3.3.7), and you just need to set some properties to enable SSL.
Of course, developers can also implement their own encryption and decryption mechanism based on certain algorithms.
The method to enable SSL in Workerman is as follows:
Preparation:
-
Workerman version is not less than 3.3.7
-
PHP has the openssl extension installed
-
A certificate has been applied for (pem/crt files and key files) and placed in the /etc/nginx/conf.d/ssl directory
Code:
<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
// It is best to use a certificate that has been applied for
$context = array(
'ssl' => array(
'local_cert' => '/etc/nginx/conf.d/ssl/server.pem', // It can also be a crt file
'local_pk' => '/etc/nginx/conf.d/ssl/server.key',
'verify_peer' => false,
'allow_self_signed' => true, // This option needs to be enabled for self-signed certificates
)
);
// Here the websocket protocol is set; it can also be the http protocol or other protocols
$worker = new Worker('websocket://0.0.0.0:443', $context);
// Set transport to enable SSL
$worker->transport = 'ssl';
$worker->onMessage = function(TcpConnection $con, $msg) {
$con->send('ok');
};
Worker::runAll();
Enabling Server Name Indication (SNI) in Workerman
It allows multiple certificates to be bound under the same IP and port.
Merge certificate .pem and .key files:
Merge the contents of each certificate's .pem and corresponding .key files, adding the contents of the .key file to the end of the .pem file. (If the .pem file already contains the private key, this can be ignored.)
Please note that this is for a single certificate, not copying all certificates into one file.
For example, the merged pem file for host1.com.pem might look like this:
-----BEGIN CERTIFICATE-----
MIIGXTCBA...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIFBzCCA...
-----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAA....
-----END RSA PRIVATE KEY-----
Code:
<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';
$context = array(
'ssl' => array(
'SNI_enabled' => true, // Enable SNI
'SNI_server_certs' => [ // Set multiple certificates
'host1.com' => '/path/host1.com.pem', // Certificate 1
'host2.com' => '/path/host2.com.pem', // Certificate 2
],
'local_cert' => '/path/default.com.pem', // Default certificate
'local_pk' => '/path/default.com.key',
)
);
$worker = new Worker('websocket://0.0.0.0:443', $context);
$worker->transport = 'ssl';
$worker->onMessage = function(TcpConnection $con, $msg) {
$con->send('ok');
};
Worker::runAll();