Help Center/ Intelligent EdgeFabric/ User Guide/ User Guide (Platinum)/ End Device Management/ Performing Security Authentication Using Certificate
Updated on 2024-09-05 GMT+08:00

Performing Security Authentication Using Certificate

Scenario

By default, the built-in MQTT broker enables the port for Transport Layer Security (TLS) authentication. A client can access the MQTT broker only when it has a certificate.

End devices and applications can use the certificates added on the node details page for security authentication.

Applications deployed in a node group may be scheduled onto any node in the node group. End devices may also access any node in the node group. The certificates added on the node details page cannot implement access to the MQTT broker on nodes from applications. Therefore, a node group certificate is required. For details on how to add a node group certificate, see Adding a Node Group Certificate.

Constraints

  • Certificates are bound to edge nodes. The certificates applied for on an edge node can be used only to access the MQTT broker of this edge node. If these certificates are used to access the MQTT broker of another edge node, the authentication will fail.
  • A maximum of 10 certificates can be applied for an edge node.
  • The validity period of a certificate is 5 years.
  • There are constraints on using MQTT.
    Table 1 MQTT constraints

    Description

    Restriction

    Supported MQTT version

    3.1.1

    Differences from the standard MQTT protocol

    • Quality of Service (QoS) 0 is supported.
    • Topic customization is supported.
    • QoS 1 and QoS 2 are not supported.
    • will and retain messages are not supported.

    MQTTS security levels

    TCP channel basic + TLS protocol (TLS v1.2)

Applying for a Certificate

The validity period of a certificate is 5 years.

  1. Log in to the IEF console, and click Switch Instance on the Dashboard page to select a platinum service instance.
  2. In the navigation pane, choose Managed Resources > Edge Nodes.
  3. Click an edge node name. The edge node details page is displayed.
  4. Click the Certificates tab, and click Add Certificate.
  5. Enter a certificate name and click OK.

    After the certificate is added, the system will automatically download the certificate file. Keep the certificate file secure.

    Figure 1 Adding a certificate

Using a Certificate

A certificate is used for authentication when an end device communicates with the MQTT broker.

Go-Language Code Sample and Java-Language Code Sample illustrate how to use certificates for authentication.

  • The client does not need to verify the server certificate. In other words, one-way authentication is required.
  • Port 8883 of the built-in MQTT broker is enabled by default.
  • In the Go-language code sample, the MQTT client references github.com/eclipse/paho.mqtt.golang (an open-source library).
  • The MQTT client is required to process disconnection events and reestablish connections to improve the connection reliability.

Go-Language Code Sample

package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"math/rand"
	"sync"
	"time"

	MQTT "github.com/eclipse/paho.mqtt.golang"
)

func main() {
	subClient := InitMqttClient(onSubConnectionLost)
	pubClient := InitMqttClient(onPubConnectionLost)

	wait := sync.WaitGroup{}
	wait.Add(1)

	go func() {
		for {
			time.Sleep(1*time.Second)
			pubClient.Publish("topic", 0, false, "hello world")
		}
	}()

	subClient.Subscribe("topic", 0, onReceived)

	wait.Wait()
}

func InitMqttClient(onConnectionLost MQTT.ConnectionLostHandler) MQTT.Client {
	pool := x509.NewCertPool()
	cert, err := tls.LoadX509KeyPair("/tmp/example_cert.crt", "/tmp/example_cert.key")
	if err != nil {
		panic(err)
	}

	tlsConfig := &tls.Config{
		RootCAs: pool,
		Certificates: []tls.Certificate{cert},
 		// One-way authentication, that is, the client does not verify the server certificate.
		InsecureSkipVerify: true,
	}
    // Use the TLS or SSL protocol to connect to port 8883.
	opts := MQTT.NewClientOptions().AddBroker("tls://127.0.0.1:8883").SetClientID(fmt.Sprintf("%f",rand.Float64()))
	opts.SetTLSConfig(tlsConfig)
	opts.OnConnect = onConnect
	opts.AutoReconnect = false
	// Callback function. It is triggered immediately after the client is disconnected from the server.
	opts.OnConnectionLost = onConnectionLost
	client := MQTT.NewClient(opts)
	loopConnect(client)
	return client
}

func onReceived(client MQTT.Client, message MQTT.Message) {
	fmt.Printf("Receive topic: %s,  payload: %s \n", message.Topic(), string(message.Payload()))
}

// The reconnection mechanism is triggered after the subscribe client is disconnected from the server.
func onSubConnectionLost(client MQTT.Client, err error) {
	fmt.Println("on sub connect lost, try to reconnect")
	loopConnect(client)
	client.Subscribe("topic", 0, onReceived)
}

// The reconnection mechanism is triggered after the publish client is disconnected from the server.
func onPubConnectionLost(client MQTT.Client, err error) {
	fmt.Println("on pub connect lost, try to reconnect")
	loopConnect(client)
}

func onConnect(client MQTT.Client) {
	fmt.Println("on connect")
}

func loopConnect(client MQTT.Client) {
	for {
		token := client.Connect()
		if rs, err := CheckClientToken(token); !rs {
			fmt.Printf("connect error: %s\n", err.Error())
		} else {
			break
		}
		time.Sleep(1 * time.Second)
	}
}

func CheckClientToken(token MQTT.Token) (bool, error) {
	if token.Wait() && token.Error() != nil {
		return false, token.Error()
	}
	return true, nil
}

Java-Language Code Sample

The format of an MqttClientDemo.java file is as follows:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
/*****************************************************************************
 Description: A java demo of MQTT message sending and receiving. You need to create an edge node and download the client certificate.
 ****************************************************************************/

package com.example.demo;

import javax.net.ssl.SSLSocketFactory;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/********************************************************************
 * MQTT demo shows how the client connects to the MQTT broker of the edge node to send and receive messages and how SSL security authentication is performed on the connection. The demo illustrates the following flows:
* 1. The MQTT subscribe client receives MQTT messages.
* 2. The MQTT publish client sends MQTT messages.
 ********************************************************************/
public class MqttClientDemo {
    private static int QOS_TYPE = 2;
    //MQTT server address
    private static final String MQTT_HOST = "ssl://x.x.x.x:8883";
    //MQTT publish client ID
    private static final String MQTT_PUB_CLIENT_ID = "pub_client_1";
    //MQTT subscribe client ID
    private static final String MQTT_SUB_CLIENT_ID = "sub_client_1";
    //MQTT channel subscription topic
    private static final String TOPIC = "/hello";
    //Paths of the SSL certificate used for MQTT client connection
    public static final String CLIENT_CRT_FILE_PATH = "example_cert.crt";
    public static final String CLIENT_KEY_FILE_PATH = "example_cert.key";
    //MQTT client connection timeout interval (s)
    public static final int TIME_OUT_INTERVAL = 10;
    //Interval at which the MQTT client sends a heartbeat message, in seconds
    public static final int HEART_TIME_INTERVAL = 20;
    //Interval at which the MQTT client retries upon disconnection, in milliseconds
    public static final int RECONNECT_INTERVAL = 10000;
    //Interval at which the MQTT client sends a message, in seconds
    public static final int PUBLISH_MSG_INTERVAL = 3000;

    //MQTT client
    private MqttClient mqttClient;
    //MQTT client ID.
    private String clientId;
    //MQTT client connection options
    private MqttConnectOptions connOpts;
    //Initialized MQTT client has not subscribed to any topic.
    private boolean isSubscribe = false;

    public MqttClientDemo(String id) throws MqttException {
        setClientId(id);
        initMqttClient();
        initCallback();
        initConnectOptions();
        connectMqtt();
    }

    /********************************************************************
     * Sending messages
     * @param message Message to be sent
     * @throws MqttException
     ********************************************************************/
    public void publishMessage(String message) throws MqttException {
        MqttMessage mqttMessage = new MqttMessage(message.getBytes());
        mqttMessage.setQos(QOS_TYPE);
        mqttMessage.setRetained(false);
        mqttClient.publish(TOPIC, mqttMessage);
        System.out.println(String.format("MQTT Client[%s] publish message[%s]", clientId, message));
    }

    /********************************************************************
     * Subscribing to topics
     * @throws MqttException
     ********************************************************************/
    public void subscribeTopic() throws MqttException {
        int[] Qos = {QOS_TYPE};
        String[] topics = {TOPIC};
        mqttClient.subscribe(topics, Qos);
        isSubscribe = true;
    }

    /********************************************************************
     * Starting the thread to periodically send MQTT messages
     * @throws MqttException
     ********************************************************************/
    public void startPublishMessage() {
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(PUBLISH_MSG_INTERVAL);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        publishMessage("hello world!");
                    } catch (MqttException e) {
                        System.out.println(String.format("MQTT client[%s] publish message error,errorMsg[%s]", clientId, e.getMessage()));
                    }
                }
            }
        }.start();
    }

    /********************************************************************
     * Initializing the MQTT client
     * @throws MqttException Abnormal connection
     ********************************************************************/
    private void initMqttClient() throws MqttException {
        MemoryPersistence persistence = new MemoryPersistence();
        mqttClient = new MqttClient(MQTT_HOST, clientId, persistence);
    }

    /********************************************************************
     * Initializing connection options
     * @throws MqttException Abnormal connection
     ********************************************************************/
    private void initConnectOptions() {
        connOpts = new MqttConnectOptions();
        // Specify whether to clear the session. If the value is false, the server retains the client connection records. If the value is true, the client connects to the server as a new client.
        connOpts.setCleanSession(true);
        connOpts.setHttpsHostnameVerificationEnabled(false);
        // Set the timeout interval, in seconds.
        connOpts.setConnectionTimeout(TIME_OUT_INTERVAL);
        // Set the interval at which a session heartbeat message is sent, in seconds. The server sends a message to the client every 1.5x20 seconds to check whether the client is online. However, this method does not provide the reconnection mechanism.
        connOpts.setKeepAliveInterval(HEART_TIME_INTERVAL);
        SSLSocketFactory factory = null;
        try {
            factory = SslUtil.getSocketFactory(CLIENT_CRT_FILE_PATH, CLIENT_KEY_FILE_PATH);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // TLS connection configuration
        connOpts.setSocketFactory(factory);
    }

    /********************************************************************
     * Initiate an MQTT connect request.
     * @throws MqttException Abnormal connection
     ********************************************************************/
    private void connectMqtt() throws MqttException {
        mqttClient.connect(connOpts);
        System.out.println(String.format("MQTT client[%s] is connected,the connctOptions: \n%s", clientId, connOpts.toString()));
    }

    /********************************************************************
     * Set the callback API.
     * @throws MqttException Abnormal connection
     ********************************************************************/
    private void initCallback() {
        mqttClient.setCallback(new MqttMessageCallback());
    }

    private void setClientId(String id) {
        clientId = id;
    }

    /********************************************************************
     * MQTT client reconnection function. This function is called to check whether a topic has been subscribed to. If yes, the topic will be re-subscribed to.
     * @throws MqttException
     ********************************************************************/
    private void rconnectMqtt() throws MqttException {
        connectMqtt();
        if (isSubscribe) {
            subscribeTopic();
        }
    }

    /********************************************************************
     * After the MQTT client subscribes to topics, the MQTT client receives messages through the callback API if the MQTT channel has data.
     * @version V1.0
     ********************************************************************/
    private class MqttMessageCallback implements MqttCallback {

        @Override
        public void connectionLost(Throwable cause) {
            System.out.println(String.format("MQTT Client[%s] connect lost,Retry in 10 seconds,info[%s]", clientId, cause.getMessage()));
            while (!mqttClient.isConnected()) {
                try {
                    Thread.sleep(RECONNECT_INTERVAL);
                    System.out.println(String.format("MQTT Client[%s] reconnect ....", clientId));
                    rconnectMqtt();
                } catch (Exception e) {
                    continue;
                }
            }

        }

        @Override
        public void messageArrived(String topic, MqttMessage mqttMessage) {
            String message = new String(mqttMessage.getPayload());
            System.out.println(String.format("MQTT Client[%s] receive message[%s] from topic[%s]", clientId, message, topic));
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

        }
    }


    public static void main(String[] args) throws MqttException {
        try {
           //Subscribe to the MQTT channel.
            MqttClientDemo mqttsubClientDemo = new MqttClientDemo(MqttClientDemo.MQTT_SUB_CLIENT_ID);
            mqttsubClientDemo.subscribeTopic();
            //Send hello world to the MQTT channel.
            MqttClientDemo mqttpubClientDemo = new MqttClientDemo(MqttClientDemo.MQTT_PUB_CLIENT_ID);
            mqttpubClientDemo.startPublishMessage();
        } catch (MqttException e) {
            System.out.println(String.format("program start error,errorMessage[%s]", e.getMessage()));
        }
    }
}

The format of an SSLUtil.java file is as follows:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
/*****************************************************************************
 Description: SSL utility class. Load the client SSL certificate configuration and ignore server certificate verification.
 ****************************************************************************/

package com.example.demo;

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMReader;
import org.bouncycastle.openssl.PasswordFinder;

public class SslUtil {


    /********************************************************************
     * Verify and obtain the SSLSocketFactory.
     ********************************************************************/
    public static SSLSocketFactory getSocketFactory(final String crtFile, final String keyFile) throws Exception {
        Security.addProvider(new BouncyCastleProvider());

        // 1. Load the client certificate.
        PEMReader reader_client =
                new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))));
        X509Certificate cert = (X509Certificate) reader_client.readObject();
        reader_client.close();

        // 2. Load the client key.
        reader_client = new PEMReader(
                new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))),
                new PasswordFinder() {
                    @Override
                    public char[] getPassword() {
                        return null;
                    }
                }
        );

        // 3. Send the client key and certificate to the server for identity authentication.
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setCertificateEntry("certificate", cert);
        ks.setKeyEntry("private-key", ((KeyPair) reader_client.readObject()).getPrivate(), "".toCharArray(), new Certificate[]{cert});
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, "".toCharArray());

        // 4. Create a socket factory.
        SSLContext context = SSLContext.getInstance("TLSv1.2");
        TrustManager[] tms = new TrustManager[1];
        TrustManager miTM = new TrustAllManager();
        tms[0] = miTM;
        context.init(kmf.getKeyManagers(), tms, null);

        reader_client.close();

        return context.getSocketFactory();
    }


    /********************************************************************
     * Ignore server certificate verification.
     ********************************************************************/
    static class TrustAllManager implements TrustManager, X509TrustManager {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
        }

        public boolean isServerTrusted(X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(X509Certificate[] certs) {
            return true;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
        }
    }
}

The format of a pom.xml file is as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>mqtt.example</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>7</source>
                    <target>7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
    <!-- https://mvnrepository.com/artifact/org.eclipse.paho/org.eclipse.paho.client.mqttv3 -->
    <dependency>
        <groupId>org.eclipse.paho</groupId>
        <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
        <version>1.2.1</version>
    </dependency>
     <!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk16 -->
    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcprov-jdk16</artifactId>
        <version>1.45</version>
    </dependency>
    </dependencies>

</project>