Help Center> IoT Device Access> Best Practices> Device Access> Connecting a Device That Uses the X.509 Certificate Based on MQTT.fx
Updated on 2024-04-29 GMT+08:00

Connecting a Device That Uses the X.509 Certificate Based on MQTT.fx

This topic uses MQTT.fx as an example to describe how to connect devices to IoTDA using the native MQTT protocol. MQTT.fx is a widely used MQTT client. Using MQTT.fx, you can easily verify whether devices can interact with IoTDA to publish or subscribe to messages.

An X.509 certificate is a digital certificate used for communication entity authentication. IoTDA allows devices to use their X.509 certificates for authentication. The use of X.509 certificate authentication protects devices from being spoofed.

Prerequisites

  • You have registered a Huawei Cloud account. If you have not registered, click here to complete the registration.
  • You have subscribed to the IoTDA service. If you have not subscribed to the service, go to the IoTDA service page, and click Access Console to subscribe to the service.

Constraints

  • Only MQTT devices can use X.509 certificates for identity authentication.
  • You can upload a maximum of 100 device CA certificates.

X.509-based Authentication

  • The complete two-way certificate authentication is as follows:

  • Two-way certificate authentication:

Obtaining Device Access Information

Perform the following procedure to obtain device access information on the IoTDA console:

  1. Log in to the IoTDA console.
  2. In the navigation pane, choose Overview and click Access Details in the Instance Information area to view the device access information and record domain names and ports.

    Figure 1 Platform access addresses

    For devices that cannot be connected to the platform using a domain name, run the ping Domain name command in the CLI to obtain the corresponding IP address. Then you can connect the devices to the platform using the IP address. The IP address is variable and needs to be set using a configuration item.

Creating a Product

  1. Log in to the console, choose Products in the navigation pane, and click Create Product on the left.

    Figure 2 Creating a product

  2. Set the parameters as prompted and click OK.

    Basic Information

    Resource Space

    The platform automatically allocates the created product to the default resource space. If you want to allocate the product to another resource space, select the resource space from the drop-down list. If a resource space does not exist, create it first.

    Product Name

    Customize the value. The name can contain letters, numbers, underscores (_), and hyphens (-).

    Protocol

    Select MQTT.

    Data Type

    Select JSON.

    Industry

    Set this parameter based on the site requirements. If the product model preset on the platform is used, set this parameter based on the industry to which the product model belongs. If not, select Default.

    Device Type

    Set this parameter based on the site requirements. If the product model preset on the platform is used, the device type is automatically matched.

    Advanced Settings

    Product ID

    Set a unique identifier for the product. If this parameter is specified, the platform uses the specified product ID. If this parameter is not specified, the platform allocates a product ID.

    Figure 3 Creating an MQTT product

Developing a Product Model

  1. Click the created product. The product details page is displayed.
  2. On the Model Definition tab page of the product details page, click Custom Model to add services of the product.
  3. Add the Connectivity service.

    1. On the Add Service page, configure Service ID, Service Type, and Description, and click OK.
      • Service ID: Enter Connectivity.
      • Service Type: You are advised to set this parameter to the same value as Service ID.
      • Description: Enter Connectivity.
        Figure 4 Adding a service
    2. Choose Connectivity, click Add Property, enter related information, and click OK.
      • Property Name: Enter dailyActivityTime.
      • Data Type: Select Integer.
      • Access Permissions: Select Read.
      • Value Range: Set it to 0–65535.
      • Step: Enter 1.
      • Unit: Enter s.
        Figure 5 Adding a property

  4. Add the Battery service.

    1. On the Model Definition tab page, click Add Service, configure Service ID, Service Type, and Description, and click OK.
      • Service ID: Enter Battery.
      • Service Type: You are advised to set this parameter to the same value as Service ID.
      • Description: Enter Battery.
        Figure 6 Adding a service
    2. Choose Battery, click Add Property, enter related information, and click OK.
      • Property Name: Enter batteryLevel.
      • Data Type: Select Integer.
      • Access Permissions: Select Read.
      • Value Range: Set it to 0–100.
      • Step: Enter 1.
      • Unit: Enter %.
        Figure 7 Adding a property

Uploading a Device CA certificate

  1. In the left navigation pane, choose Devices > Device CA Certificates, and click Upload Certificate in the upper right corner.
  2. In the displayed dialog box, click Select File to add a file, and then click OK.

    Figure 8 Uploading a certificate
    • Device CA certificates are provided by device vendors. You can prepare a commissioning certificate during commissioning. For security reasons, you are advised to replace the commissioning certificate with a commercial certificate during commercial use.
    • CA certificates cannot be used to verify server certificates upon expiration. Replace these certificates before expiration dates to ensure that devices can connect to the IoT platform properly.

Making a Device CA Commissioning Certificate

This section uses the Windows operating system as an example to describe how to use OpenSSL to make a commissioning certificate. The generated certificate is in PEM format.

  1. Download and install OpenSSL.
  2. Open the CLI as user admin.
  3. Run cd c:\openssl\bin (replace c:\openssl\bin with the actual OpenSSL installation directory) to access the OpenSSL view.
  4. Generate a public/private key pair.
    openssl genrsa -out rootCA.key 2048
  5. Use the private key in the key pair to generate a CA certificate.
    openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem

    The system prompts you to enter the following information. All the parameters can be customized.

    • Country Name (2 letter code) [AU]: country, for example, CN

    • State or Province Name (full name) []: state or province, for example, GD

    • Locality Name (for example, city) []: city, for example, SZ

    • Organization Name (for example, company) []: organization, for example, Huawei

    • Organizational Unit Name (for example, section) []: organization unit, for example, IoT

    • Common Name (e.g. server FQDN or YOUR name) []: common name, for example, zhangsan

    • Email Address []: email address, for example, 1234567@163.com

    Obtain the generated CA certificate rootCA.pem from the bin folder in the OpenSSL installation directory.

Uploading a Verification Certificate

If the uploaded certificate is a commissioning certificate, the certificate status is Unverified. In this case, upload a verification certificate to verify that you have the CA certificate.

Figure 9 Device CA certificate

The verification certificate is created based on the private key of the device CA certificate. Perform the following operations to create a verification certificate:

  1. Obtain the verification code to verify the certificate.

    Figure 10 Uploading a verification certificate
    Figure 11 Obtaining a verification code

  2. Generate a key pair for the verification certificate.

    openssl genrsa -out verificationCert.key 2048

  3. Create a certificate signing request (CSR) for the verification certificate.

    openssl req -new -key verificationCert.key -out verificationCert.csr

    The system prompts you to enter the following information. Set Common Name to the verification code and set other parameters as required.

    • Country Name (2 letter code) [AU]: country, for example, CN

    • State or Province Name (full name) []: state or province, for example, GD

    • Locality Name (for example, city) []: city, for example, SZ

    • Organization Name (for example, company) []: organization, for example, Huawei

    • Organizational Unit Name (for example, section) []: organization unit, for example, IoT

    • Common Name (e.g. server FQDN or YOUR name) []: verification code for verifying the certificate. For details on how to obtain the verification code, see 1.

    • Email Address []: email address, for example, 1234567@163.com

    • Password[]: password, for example, 1234321
    • Optional Company Name[]: company name, for example, Huawei

  4. Use the CSR to create a verification certificate.

    openssl x509 -req -in verificationCert.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out verificationCert.pem -days 500 -sha256

    Obtain the generated verification certificate verificationCert.pem from the bin folder of the OpenSSL installation directory.

  5. Locate the target certificate, click , and click Upload Verification Certificate.

    Figure 12 Uploading a verification certificate

  6. In the displayed dialog box, click Select File to add a file, and then click OK.

    Figure 13 Completing verification

    After the verification certificate is uploaded, the certificate status changes to Verified, indicating that you have the CA certificate.

Presetting an X.509 Certificate

Before registering an X.509 device, preset the X.509 certificate issued by the CA on the device.

The X.509 certificate is issued by the CA. If no commercial certificate issued by the CA is available, you can create a device CA commissioning certificate.

Creating an X.509 Commissioning Certificate

  1. Run cmd as user admin to open the CLI and run cd c:\openssl\bin (replace c:\openssl\bin with the actual OpenSSL installation directory) to access the OpenSSL view.
  2. Generate a public/private key pair.
    openssl genrsa -out deviceCert.key 2048
  3. Create a CSR.
    openssl req -new -key deviceCert.key -out deviceCert.csr

    The system prompts you to enter the following information. All the parameters can be customized.

    • Country Name (2 letter code) [AU]: country, for example, CN

    • State or Province Name (full name) []: state or province, for example, GD

    • Locality Name (for example, city) []: city, for example, SZ

    • Organization Name (for example, company) []: organization, for example, Huawei

    • Organizational Unit Name (for example, section) []: organization unit, for example, IoT

    • Common Name (e.g. server FQDN or YOUR name) []: common name, for example, zhangsan

    • Email Address []: email address, for example, 1234567@163.com

    • Password[]: password, for example, 1234321
    • Optional Company Name[]: company name, for example, Huawei
  4. Create a device certificate using CSR.
    openssl x509 -req -in deviceCert.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out deviceCert.pem -days 500 -sha256

    Obtain the generated device certificate deviceCert.pem from the bin folder in the OpenSSL installation directory.

Registering a Device Authenticated by an X.509 Certificate

  1. Log in to the IoTDA console.
  2. In the navigation pane, choose Devices > All Devices, click Individual Register in the upper right corner, set parameters based on the table below, and click OK.

    Figure 14 Registering a device

    Parameter

    Description

    Resource Space

    Select the resource space to which a device belongs.

    Product

    Select the product to which the device belongs.

    If no product is available, create a product first.

    Node ID

    Set this parameter to the IMEI, MAC address, or serial number of the device. If the device is not a physical one, set this parameter to a custom character string that contains letters and digits.

    Device Name

    Customize the device name.

    Authentication Type

    X.509 certificate: The device uses an X.509 certificate for identity verification.

    Fingerprint

    This parameter is displayed when Authentication Type is set to X.509 certificate. Import the fingerprint corresponding to the preset device certificate on the device side. You can run openssl x509 -fingerprint -sha256 -in deviceCert.pem in the OpenSSL view to query the fingerprint. Note: Delete the colon (:) from the obtained fingerprint when filling it.

Performing Connection Authentication

You can activate the device registered with the platform by using MQTT.fx. For details, see Device Connection Authentication.

  1. Download MQTT.fx (64-bit OS) or MQTT.fx (32-bit OS) and install it.

    • Install the latest MQTT.fx tool. Download it.
    • MQTT.fx 1.7.0 and earlier versions have problems in processing topics containing $. Use the latest version for test.

  2. Go to the IoTDA client ID generator page, enter the device ID and secret generated after registering a device to generate connection information (including ClientId, Username, and Password).

    You can set DeviceSecret to any value, for example, 12345678.

    Figure 15 Obtaining ClientId

    Parameter

    Mandatory

    Type

    Description

    ClientId

    Yes

    String(256)

    The value of this parameter consists of a device ID, device type, password signature type, and timestamp. They are separated by underscores (_).

    • Device ID: A device ID uniquely identifies a device and is generated when the device is registered with IoTDA. The value usually consists of a device's product ID and node ID which are separated by an underscore (_).
    • Device type: The value is fixed at 0, indicating a device ID.
    • Password signature type: The length is 1 byte, and the value can be 0 or 1.
      • 0: The timestamp is not verified using the HMAC-SHA256 algorithm.
      • 1: The timestamp is verified using the HMAC-SHA256 algorithm.
    • Timestamp: The UTC time when the device was connected to IoTDA. The format is YYYYMMDDHH. For example, if the UTC time is 2018/7/24 17:56:20, the timestamp is 2018072417.

    Username

    Yes

    String(256)

    Device ID.

    Each device performs authentication using the MQTT CONNECT message, which must contain all information of the client ID. After receiving a CONNECT message, IoTDA checks the authentication type and password digest algorithm of the device.

    The generated client ID is in the format Device ID_0_0_Timestamp. By default, the timestamp is not verified.

    • If the timestamp needs to be verified using the HMAC-SHA256 algorithm, the platform checks whether the message timestamp is consistent with the platform time and then checks whether the password is correct.
    • If the timestamp does not need to be verified using the HMAC-SHA256 algorithm, the timestamp must also be contained in the CONNECT message, but the platform does not check whether the time is correct. In this case, only the password is checked.

    If the authentication fails, the platform returns an error message and automatically disconnects the MQTT connections.

  3. Open the MQTT.fx tool and click the setting icon.

    Figure 16 Settings

  4. Enter Connection Profile information.

    Figure 17 Using default settings for parameters on the General tab page

    Parameter

    Description

    Broker Address

    Enter the device access address (domain name) obtained from the IoTDA console. If the device cannot be connected using a domain name, enter the IP address obtained in 2.

    Broker Port

    Enter 8883.

    Client ID

    Enter the device client ID obtained in 2.

  5. Click User Credentials and specify User Name.

    Figure 18 Entering the device ID

    Parameter

    Description

    User Name

    Enter the device ID obtained in 2.

    Password

    Leave it blank when the X.509 certificate is used for authentication.

  6. Click SSL/TLS, set authentication parameters, and click Apply. Select Enable SSL/TLS, select Self signed certificates, and enter the certificate information.

    Figure 19 Setting SSL/TLS parameters

    CA File: corresponding CA certificate. Download the certificate from Obtaining Resources and load the PEM certificate.

    Client Certificate File: device certificate (deviceCert.pem).

    Client Key File: private key (deviceCert.key) of the device.

  7. Click Connect. If the device authentication is successful, the device is displayed online on the platform.

    Figure 20 Device status

Reporting Data

Use MQTT.fx to report data to the platform. For details, see Reporting Device Properties in the API Reference.

If the device reports data through the MQTT channel, the data must be sent to the specified topic. The format of the topic for reporting the data is $oc/devices/{device_id}/sys/properties/report, where {device_id} is the device ID returned after device registration.

  1. Enter the API address in the format of "$oc/devices/{device_id}/sys/properties/report", for example, $oc/devices/5e4e2e92ac-164aefa8fouquan1/sys/properties/report.

    Figure 21 Entering the API address

  2. Enter the data to report.

    Request parameters

    Parameter

    Mandatory

    Type

    Description

    services

    Yes

    List<ServiceProperty>

    Service data list. (For details, see the ServiceProperty structure below.)

    ServiceProperty structure

    Parameter

    Mandatory

    Type

    Description

    service_id

    Yes

    String

    Service ID.

    properties

    Yes

    Object

    Service properties, which are defined in the product model of the device.

    event_time

    No

    String

    UTC time when the device reports data. The format is yyyyMMddTHHmmssZ, for example, 20161219T114920Z.

    If this parameter is not carried in the reported data or is in incorrect format, the time when IoTDA receives the data is used.

    Example request

    {
        "services": [{
                "service_id": "Connectivity",
                "properties": {
                    "dailyActivityTime": 57
                },
                "event_time": "20151212T121212Z"
            },
            {
                "service_id": "Battery",
                "properties": {
                    "batteryLevel": 80
                },
                "event_time": "20151212T121212Z"
            }
        ]
    }
    Figure 22 Example request

  3. Click Publish. Then you can check whether the device successfully reports data on the platform.

    Figure 23 Reporting data