From 82581417df4fa63a95c7584866a8fd2fdef53105 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9?= Date: Wed, 24 Apr 2024 18:24:36 +0200 Subject: [PATCH] Added support for TLS ALPN to connect via MQTT protocol to a TLS encrypted HTTP port 443 (#181) * Update ConnectionSettings.php added TLS ALPN option * Update MqttClient.php Added TLS ALPN option to the TLS options * Update MqttClient.php * Update README.md Added TLS ALPN to the ConnectSettings options --- README.md | 4 ++++ src/ConnectionSettings.php | 22 ++++++++++++++++++++++ src/MqttClient.php | 4 ++++ 3 files changed, 30 insertions(+) diff --git a/README.md b/README.md index f171d4d..8c87eb3 100644 --- a/README.md +++ b/README.md @@ -243,6 +243,10 @@ $connectionSettings = (new \PhpMqtt\Client\ConnectionSettings) // This option requires ConnectionSettings::setTlsClientCertificateFile() and // ConnectionSettings::setTlsClientCertificateKeyFile() to be used as well. ->setTlsClientCertificateKeyPassphrase(null); + + // The TLS ALPN is used to establish a TLS encrypted mqtt connection on port 443, + // which usually is reserved for TLS encrypted HTTP traffic. + ->setTlsAlpn(null); ``` ## Features diff --git a/src/ConnectionSettings.php b/src/ConnectionSettings.php index 864522f..b69a6f2 100644 --- a/src/ConnectionSettings.php +++ b/src/ConnectionSettings.php @@ -37,6 +37,7 @@ class ConnectionSettings private ?string $tlsClientCertificateFile = null; private ?string $tlsClientCertificateKeyFile = null; private ?string $tlsClientCertificateKeyPassphrase = null; + private ?string $tlsAlpn = null; /** * The username used for authentication when connecting to the broker. @@ -531,4 +532,25 @@ public function getTlsClientCertificateKeyPassphrase(): ?string { return $this->tlsClientCertificateKeyPassphrase; } + + /** + * The TLS ALPN is used to establish a TLS encrypted mqtt connection on port 443, + * which usually is reserved for TLS encrypted HTTP traffic. + * + * @return ConnectionSettings A copy of the original object with the new setting applied. + */ + public function setTlsAlpn(?string $tlsAlpn): ConnectionSettings + { + $copy = clone $this; + + $copy->tlsAlpn = $tlsAlpn; + + return $copy; + } + + public function getTlsAlpn(): ?string + { + return $this->tlsAlpn; + } + } diff --git a/src/MqttClient.php b/src/MqttClient.php index 4064804..1bb296c 100644 --- a/src/MqttClient.php +++ b/src/MqttClient.php @@ -197,6 +197,10 @@ protected function establishSocketConnection(): void $tlsOptions['passphrase'] = $this->settings->getTlsClientCertificateKeyPassphrase(); } + if ($this->settings->getTlsAlpn() !== null) { + $tlsOptions['alpn_protocols'] = $this->settings->getTlsAlpn(); + } + $contextOptions['ssl'] = $tlsOptions; }