Remotely access devices via secure tunnel
Some Internet of Things (IoT) devices cannot be accessed directly from the internet for security reasons or because they are deployed on a private network. The IoT Platform secure tunnel feature establishes a secure, bidirectional communication channel, allowing you to remotely access, diagnose, and manage your devices.
Background
You can use the secure tunnel feature of IoT Platform to remotely log in to existing services on a device. For example, if a device has diagnostic capabilities accessible via host computer software, you can use the secure tunnel service's remote connection feature to perform remote diagnostics.
For more information about the use cases and instructions for secure tunnels, see Secure tunnel overview.
This topic uses a device running Linux as an example to demonstrate how to remotely access the device by using a secure tunnel.
In this example, you create the secure tunnel manually in the console. You can use this example as a reference to develop remote access features for local services on your devices based on your business requirements.
Device-side development
Prerequisites
-
Obtain device authentication information.
This example uses device-specific authentication and requires the following device credential triplet:
{ "ProductKey": "a1WvA***", "DeviceName": "device2", "DeviceSecret": "ff01e59d***ba2ca2b17" } -
When you customize the SDK, on the SDK Customization page, select Remote Login in the Advanced Features section to integrate the secure tunnel feature with the device-side SDK.
-
Prepare the development environment.
This example uses a Linux development environment with the Xinetd service installed, which can launch an Echo service process on port 7.
ImportantIn this example, data communication between the device and the access side depends on the Xinetd service. Therefore, you must configure and start the Xinetd service.
Start the device-side sample
-
Unzip the downloaded SDK package. In the C Link SDK, open the demo file
LinkSDK./demos/remote_access_basic_demo.c, complete the following configurations, and then save the file. For more information about device-side development with the C Link SDK, see C Link SDK overview.-
Replace the device credential information with your test device's credential triplet.
-
Replace the value of mqtt_host with the MQTT endpoint of your device's Enterprise Edition instance.
-
Add the configuration for the ECHO service to the service list. Do not delete the original _SSH service.
The following code shows the configuration information.
/* TODO: Replace with your device credential triplet. */ char *product_key = "a1xxx"; char *device_name = "device2"; char *device_secret = "xxx7"; /* * ... */ char *mqtt_host = "axxx.iot-as-mqtt.xxx.aliyuncs.com"; uint16_t port = 443; /* The destination port is 443, regardless of whether the device uses a TLS connection to IoT Platform. */ /* The set of system adaptation functions is in the portfiles/aiot_port directory. */ extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile; /* The server certificate is in external/ali_ca_cert.c. */ extern const char *ali_ca_cert; static pthread_t g_ra_process_thread; static pthread_t g_mqtt_process_thread; static pthread_t g_mqtt_recv_thread; static uint8_t g_mqtt_process_thread_running = 0; static uint8_t g_mqtt_recv_thread_running = 0; aiot_ra_service_t services[] = { { .type = "_SSH", .ip = "127.0.0.1", .port = 22, },{ .type = "ECHO", .ip = "127.0.0.1", .port = 7, } }; .type = "ECHO", .ip = "127.0.0.1", .port = 7, }, }; -
-
Log in to a Linux virtual machine (VM) and upload the modified LinkSDK files to the VM's development environment.
-
In the SDK's
/LinkSDKroot directory, run themakecommand to compile the sample program. Then, run the sample file../output/remote-access-basic-demo -
Check the run logs. The messages
MQTT connect successandremote_proxy_thread_start, along with a successful subscription to the secure tunnel topic, confirm that the device is online and the secure tunnel proxy has started.[1646291696.533][LK-1000] establish mbedtls connection with server(host='xxx.mqtt.iothub.aliyuncs.com', port=[443]) [1646291696.588][LK-1000] success to establish mbedtls connection, (cost 45247 bytes in total, max used 47983 bytes) [1646291696.677][LK-0313] MQTT connect success in 153 ms AIOT_MQTTEVT_CONNECT [1646291696.677][LK-0309] sub: /sys/xxx/device2/secure_tunnel/notify [1646291696.677][LK-1C00] remote_proxy_thread_start! -
Log in to the IoT Platform console, go to your Enterprise Edition instance, and choose Device Management > Devices in the left-side navigation pane. Find the target device and confirm that its status is Online.
Create a secure tunnel
Follow these steps to create a secure tunnel for the target device in the IoT Platform console. Alternatively, you can call the CreateDeviceTunnel API operation to create a secure tunnel. See Server-side SDKs for instructions.
-
Log in to the IoT Platform console.
-
On the Instance Overview page, click the target Enterprise Edition instance to go to the Instance Details page.
-
In the left-side navigation pane, choose Monitoring and O&M > Secure Tunnel.
-
On the Secure Tunnel page, click Create Secure Tunnel.
-
In the Create Tunnel dialog box, select a Product and a Device, enter Custom information to push to the device as needed, and click Confirm. After a secure tunnel is created, it is valid for 24 hours by default. After 24 hours, its status automatically changes to Closed, and a secure tunnel in the Closed state cannot be reopened.
-
In the dialog box that appears, click Copy All to save the secure tunnel ID, access-side token, and access-side URL. This information is shown only once, so store it securely. You cannot retrieve it after closing the dialog box.
After the secure tunnel is created, the device receives a connection notification. The secure tunnel SDK uses the information in this notification to establish a WebSocket connection with IoT Platform. The following log output from the device-side sample shows this process:
[1644310040.466][LK-1C00] _switch_topic_handler payload:{"schema":"wss","path":"/tunnel/186axxx34f/dest","token_expire":86399,"tunnel_id":"..."} ra_event_cb AIOT_RA_EVT_OPEN_WEBSOCKET 186a5 xxx 34f [1644310040.522][LK-1C00] start to create cloud channel [1644310040.522][LK-1C00] connect remote service host iot-secure-tunnel-cn-sh.aliyuncs.com, port 443establish tcp connection with server(host='iot-secure-tunnel-cn-sh.aliyuncs.com', port=[443]) success to establish tcp, fd=4 local port: 59542 [1644310040.522][LK-1000] establish mbedtls connection with server(host='iot-secure-tunnel-cn-sh.aliyuncs.com', port=[443]) [1644310040.577][LK-1000] success to establish mbedtls connection, (cost 55960 bytes in total, max used 58648 bytes) [1644310040.599][LK-0F10] open_cloud_proxy_channel success [1644310040.599][LK-1C00] websocket 186a5cxxx b53e334f opened ra_event_cb AIOT_RA_EVT_CONNECT 186a5 xxx 334f [1644310060.633][LK-1C00] websocket 186xxx4f ping [1644310060.633][LK-1C00] websocket 18xxx4f pongOn the Monitoring and O&M > Secure Tunnel page in the IoT Platform console, the secure tunnel status is Opened and the device status is Connected.
Access-side development
Prerequisites
-
Download the access-side sample code for the device's ECHO service. For more information, see alibabacloud-iot-java-demo.
-
Prepare the development environment. This example uses a Java development environment with the following specifications:
-
Operating system: Windows 10 (64-bit)
-
JDK version: JDK 8 (later versions are supported)
-
Integrated development environment (IDE): IntelliJ IDEA Community Edition
-
Start the access-side sample
-
Unzip the downloaded sample code package.
-
Open IntelliJ IDEA and import the unzipped sample project.
-
In the
com.aliyun.iotx.lp.demo.secure.tunnel.echo.EchoServiceDemoTunnelSourceTest.javafile, set the saved secure tunnel ID, access-side token, and access-side URL.Replace
tunnelId,sourceUri, andsourceTokenwith your device tunnel information. The following code shows an example:import ... /** * this is the example for echo service using the device tunnel of aliyun iot */ public class EchoServiceDemoTunnelSourceTest { public static void main(String[] args) throws InterruptedException, JoranException, IOException { load(EchoServiceDemoTunnelSourceTest.class.getClassLoader().getResource("logback-spring.xml").getPath()); String tunnelId = "186axxx...xxxe334f"; String sourceUri = "wss://iot-secure-tunnel-cn-sh.aliyuncs.com/tunnel/186axxx...xxx4f/source"; String sourceToken = "f32dxxx...xxxaba2"; if (StringUtils.isBlank(tunnelId) || StringUtils.isBlank(sourceUri) || StringUtils.isBlank(sourceToken)) { throw new IllegalArgumentException("tunnelId, sourceUri and sourceToken should not be blank. please crate device tunnel and assign the corresponding value"); } EchoServiceDemoSourceSimulator sourceSimulator = new EchoServiceDemoSourceSimulator(tunnelId, sourceUri, sourceToken); sourceSimulator.connect(); for (int i = 0; i < 2; i++) { sourceSimulator.startEchoSession(); } Thread.sleep(20 * 1000); sourceSimulator.disconnect(); Thread.sleep(3 * 1000); } } -
Run the
EchoServiceDemoTunnelSourceTest.javasample code. After the access-side main program starts, it uses the configured connection information to establish a WebSocket connection with IoT Platform and create an ECHO-type session. The logs should resemble the following:ImportantThe sample code includes the line
Thread.sleep(20 * 1000);, which terminates the program after it has run for 20 seconds. In production, you can set the runtime as needed.18:40:59,129 |-INFO in ch.qos.logback.core.joran.action.NestedComplexPropertyIA - Assuming default type [ch.qos.logback.classic.encoder.PatternLayoutEncoder] for [encoder] property 18:40:59,158 |-INFO in ch.qos.logback.classic.joran.action.LoggerAction - Setting additivity of logger [com.aliyun.iot.secure.tunnel] to false 18:40:59,158 |-INFO in ch.qos.logback.classic.joran.action.LevelAction - com.aliyun.iot.secure.tunnel level set to DEBUG 18:40:59,158 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [console] to Logger[com.aliyun.iot.secure.tunnel] 18:40:59,158 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration. 18:40:59,158 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@10bbd20a - Registering current configuration as safe fallback point 2022-02-10 18:40:59,177 [main] DEBUG com.aliyun.iot.secure.tunnel.demo.echo.EchoServiceDemoSourceSimulator - TunnelSource is connected. tunnelId:xxx 2022-02-10 18:41:04,595 [main] INFO com.aliyun.iot.secure.tunnel.protocol.source.TunnelSource - source connect success. 2022-02-10 18:41:04,724 [tunnel-session-thread-0] INFO com.aliyun.iot.secure.tunnel.protocol.source.TunnelSource - SourceSimulator sendSessionCreateFrame header:{"service_type":"ECHO","frame_type":"SESSION_CREATE","frame_id":2170} 2022-02-10 18:41:04,724 [tunnel-session-thread-1] INFO com.aliyun.iot.secure.tunnel.protocol.source.TunnelSource - SourceSimulator sendSessionCreateFrame header:{"service_type":"ECHO","frame_type":"SESSION_CREATE","frame_id":2171} 2022-02-10 18:41:04,882 [nioEventLoopGroup-2-1] INFO com.aliyun.iot.secure.tunnel.protocol.handler.ReceivedTunnelFrameProcessor - receive success response, messageHeader={"service_type":"ECHO","session_id":"1644489532843678","frame_type":"COMMON_RESPONSE","frame_id":2171}; response={code:0,"msg":"new session response","success":true} 2022-02-10 18:41:04,883 [nioEventLoopGroup-2-1] INFO com.aliyun.iot.secure.tunnel.protocol.source.TunnelSource - source create session success. sessionId:1644489532843678 2022-02-10 18:41:04,887 [nioEventLoopGroup-2-1] INFO com.aliyun.iot.secure.tunnel.protocol.handler.ReceivedTunnelFrameProcessor - receive success response, messageHeader={"service_type":"ECHO","session_id":"1644489532843333","frame_type":"COMMON_RESPONSE","frame_id":2170}; response={code:0,"msg":"new session response","success":true} 2022-02-10 18:41:04,888 [nioEventLoopGroup-2-1] INFO com.aliyun.iot.secure.tunnel.protocol.source.TunnelSource - source create session success. sessionId:1644489532843333 2022-02-10 18:41:07,889 [tunnel-session-thread-1] DEBUG com.aliyun.iot.secure.tunnel.demo.echo.EchoServiceDemoSourceSimulator - complete to send data frame. sessionId:1644489532843678 key:payload_key_10000 2022-02-10 18:41:07,890 [tunnel-session-thread-0] DEBUG com.aliyun.iot.secure.tunnel.demo.echo.EchoServiceDemoSourceSimulator - complete to send data frame. sessionId:1644489532843333 key:payload_key_10002 2022-02-10 18:41:08,095 [nioEventLoopGroup-2-1] DEBUG com.aliyun.iot.secure.tunnel.protocol.handler.ReceivedTunnelFrameProcessor - source receive data-trans-frame, tunnelId: tunnelFrameHeader:{"service_type":"_SSH","session_id":"1644489532843333","frame_type":"DATA_TRANSPORT","frame_id":165328508} 2022-02-10 18:41:08,104 [nioEventLoopGroup-2-1] DEBUG com.aliyun.iot.secure.tunnel.protocol.handler.ReceivedTunnelFrameProcessor - source receive data-trans-frame, tunnelId: tunnelFrameHeader:{"service_type":"_SSH","session_id":"1644489532843678","frame_type":"DATA_TRANSPORT","frame_id":933973143} 2022-02-10 18:41:08,891 [tunnel-session-thread-0] DEBUG com.aliyun.iot.secure.tunnel.demo.echo.EchoServiceDemoSourceSimulator - complete to send data frame. sessionId:1644489532843333 key:payload_key_10004 2022-02-10 18:41:08,891 [tunnel-session-thread-1] DEBUG com.aliyun.iot.secure.tunnel.demo.echo.EchoServiceDemoSourceSimulator - complete to send data frame. sessionId:1644489532843678 key:payload_key_10005 2022-02-10 18:41:09,029 [nioEventLoopGroup-2-1] DEBUG com.aliyun.iot.secure.tunnel.protocol.handler.ReceivedTunnelFrameProcessor - source receive data-trans-frame, tunnelId: tunnelFrameHeader:{"service_type":"_SSH","session_id":"1644489532843333","frame_type":"DATA_TRANSPORT","frame_id":413190196} 2022-02-10 18:41:09,039 [nioEventLoopGroup-2-1] DEBUG com.aliyun.iot.secure.tunnel.protocol.handler.ReceivedTunnelFrameProcessor - source receive data-trans-frame, tunnelId: tunnelFrameHeader:{"service_type":"_SSH","session_id":"1644489532843678","frame_type":"DATA_TRANSPORT","frame_id":643528316} 2022-02-10 18:41:09,892 [tunnel-session-thread-0] DEBUG com.aliyun.iot.secure.tunnel.demo.echo.EchoServiceDemoSourceSimulator - complete to send data frame. sessionId:1644489532843333 key:payload_key_10008 2022-02-10 18:41:09,892 [tunnel-session-thread-1] DEBUG com.aliyun.iot.secure.tunnel.demo.echo.EchoServiceDemoSourceSimulator - complete to send data frame. sessionId:1644489532843678 key:payload_key_10009 2022-02-10 18:41:10,073 [nioEventLoopGroup-2-1] DEBUG com.aliyun.iot.secure.tunnel.protocol.handler.ReceivedTunnelFrameProcessor - source receive data-trans-frame, tunnelId: tunnelFrameHeader:{"service_type":"_SSH","session_id":"1644489532843333","frame_type":"DATA_TRANSPORT","frame_id":462096631}After a session is created, you can test the device's ECHO service.