Salta al contenuto

Implementing MQTT over Port 443 with AWS IoT Core: A Simplified Approach

4 minuti di lettura
Livello di contenuto: Basico
0

This article addresses a common challenge faced by IoT developers: establishing reliable MQTT connections in environments where standard MQTT ports are restricted. Many enterprise networks and public Wi-Fi systems block non-standard ports like 8883 (MQTT) but allow traffic on port 443 (HTTPS).

By leveraging AWS IoT Core's Domain Configuration capability, developers can now implement MQTT with TLS client authentication over port 443 without complex networking workarounds.

Introduction

AWS IoT Core enables secure device connectivity over MQTT with TLS client authentication on port 443 through Domain configurations without requiring client-side code changes. This capability is particularly valuable in environments where standard MQTT ports might be restricted or blocked. For a comprehensive understanding of the advantages of connecting through port 443, please refer to our detailed blog.

While this approach is also compatible with port 8883, this article specifically focuses on implementing port 443 connectivity with X.509 certificate authentication. For comprehensive information about this capability, please review our announcement that outlines the removal of TLS Application Layer Protocol Negotiation (ALPN) requirements.

Important: When using default endpoint configurations, clients that connect on port 443 with X.509 client certificate authentication must implement the Application Layer Protocol Negotiation (ALPN) TLS extension and use the ALPN protocol name listed in the ALPN ProtocolNameList sent by the client as part of the ClientHello message.

Implementation Walkthrough

In this walkthrough, we'll demonstrate how to establish a connection and publish messages to AWS IoT Core using the Paho-MQTT client library with Python. It's worth noting that this implementation is client-agnostic. You can utilize any MQTT client library of your choice, as the only configuration adjustment required is specifying the custom IoT Endpoint generated through your Domain configuration. This flexibility allows you to integrate this solution with your existing codebase with minimal modifications.

Step 1: Install the Required Library

pip install paho-mqtt

Step 2: Prepare Device Credentials

Each connected device requires credentials to access the AWS IoT message broker. For this example, we'll use X.509 certificates for authentication. You can create an AWS IoT certificate using either the AWS IoT console or CLI. For detailed instructions, refer to the AWS IoT Developer Guide or the AWS CLI Command Reference.

Step 3: Create the Client Application

The following Python script establishes a connection to the AWS IoT endpoint and publishes timestamped messages to a topic. Save this code as iotclient_mqtt.py:

from __future__ import print_function
import sys
import ssl
import time
import datetime
import logging, traceback
import paho.mqtt.client as mqtt

aws_iot_endpoint = "AWS_IoT_ENDPOINT_HERE"  # <random>.iot.<region>.amazonaws.com

ca = "YOUR/ROOT/CA/PATH" 
cert = "YOUR/DEVICE/CERT/PATH"
private = "YOUR/DEVICE/KEY/PATH"

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
log_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(log_format)
logger.addHandler(handler)

if __name__ == '__main__':
    topic = "test/date"
    try:
        mqttc = mqtt.Client()
        ssl_context = ssl.create_default_context()
        ssl_context.load_verify_locations(cafile=ca)
        ssl_context.load_cert_chain(certfile=cert, keyfile=private)
        mqttc.tls_set_context(context=ssl_context)
        logger.info("start connect")
        mqttc.connect(aws_iot_endpoint, port=443)
        logger.info("connect success")
        mqttc.loop_start()

        while True:
            time.sleep(1)
            now = datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S')
            logger.info("try to publish:{}".format(now))
            mqttc.publish(topic, now)            

    except Exception as e:
        logger.error("exception main()")
        logger.error("e obj:{}".format(vars(e)))
        logger.error("message:{}".format(e.message))
        traceback.print_exc(file=sys.stdout)

Step 4: Create a Custom Domain Configuration

Create a custom endpoint named "MqttOver443" with X.509 authentication and MQTT protocol using the AWS CLI:

aws iot create-domain-configuration --domain-configuration-name MqttOver443 --authentication-type AWS_X509 --application-protocol SECURE_MQTT

You should receive a response similar to:

{
    "domainConfigurationName": "MqttOver443",
    "domainConfigurationArn": "<ARN>"
}

Step 5: Retrieve the IoT Endpoint for Your Domain

Obtain the IoT endpoint for your newly created domain:

aws iot describe-domain-configuration --domain-configuration-name MqttOver443

The response will include your IoT endpoint/domainName. Replace the placeholder in your Python script with this endpoint and update the certificate paths.

Step 6: Run the Python Script

Execute the script:

python3 iotclient_mqtt.py

When you see "connect success" and "published:<timestamp>" messages in the console, you've successfully established a connection to AWS IoT Core and published messages.

If you encounter errors, verify your AWS IoT endpoint and certificate information.

Step 7: Verify Message Reception

To confirm that AWS IoT is receiving your client messages:

  1. Sign in to the AWS IoT console
  2. Navigate to the MQTT test client in the left navigation pane
  3. Choose "Subscribe to a topic" and enter "test/date"
  4. After subscribing, you should see the messages published by your client device

Conclusion

This tutorial demonstrates how to use AWS IoT Domain configurations to connect to AWS IoT Core on port 443 using MQTT with TLS client authentication. By creating a custom Domain configuration as shown above, you can connect any MQTT client to port 443 without additional code modifications. This approach simplifies secure device connectivity in environments where standard MQTT ports might be restricted.

AWS
ESPERTO
pubblicato 3 mesi fa309 visualizzazioni