Local proxy for remote device access using secure tunnels
Some Internet of Things (IoT) devices cannot be accessed from the public internet for security reasons or because they are in a private network (VPC). The secure tunnel feature of IoT Platform establishes a bidirectional communication link, which you can use to remotely access, diagnose, and manage your devices.
Background information
The secure tunnel feature of IoT Platform lets you remotely access local device services through an access-side proxy. These services include Secure Shell (SSH) logon, Remote Desktop Protocol (RDP) control, and other services on the device.
For more information about the scenarios and instructions for secure tunnels, see Secure tunnel overview.
This topic uses a Linux device as an example to show how to access local device services using an access-side proxy.
In the example in this topic, the secure tunnel is created manually in the console. However, you can also use the access-side proxy method from this example to develop your own application and integrate the Alibaba Cloud IoT Platform cloud APIs to automatically create secure tunnels.
How it works
This example shows how to access the SSH service on a Linux device. The following figure illustrates the process.
Instructions
The steps in the diagram are explained as follows:
Step | Description |
1, 2, 3 | See Device-side development and Create a secure tunnel below. Configure and start the device client, then create a secure tunnel. After the secure tunnel is created, the device client receives a tunnel connection notification and automatically connects to the IoT Platform server-side. |
4 | See Develop the access-side proxy service (Java) or Develop the access-side proxy service (Go) below. Configure and start the access-side proxy. After the proxy starts, it connects to the IoT Platform server-side as the secure tunnel's access client. |
5, 6, 7, 8, 9, 10 | See Remotely access the device through the local proxy below. Connect to the access-side proxy by running an SSH command. The proxy then starts the session creation process. After the session is created, data from the SSH client and the device-side SSHD is transmitted through the session in the secure tunnel. You can then remotely access the device. |
Device-side development
Preparations
This example uses unique-certificate-per-device authentication. The credentials that you obtain include the following information:
{ "ProductKey": "a1WvA***", "DeviceName": "device2", "DeviceSecret": "ff01e59d***ba2ca2b17" }When you customize the SDK, on the SDK Customization page, in the Advanced Features section, select Remote Logon. Selecting this option integrates the device-side SDK that includes the secure tunnel feature.
Prepare the development environment.
This example uses a Linux development environment. You must start the SSHD service process on port 22.
ImportantThe SSHD service is required for data communication when you remotely access the device from the access client. Therefore, you must configure and start the SSHD service.
Start the device-side demo
Unzip the downloaded SDK package. In the C Link SDK, open the demo file
LinkSDK/demos/remote_access_basic_demo.c. Make the following changes and save the file. For more information about device-side development with the C Link SDK, see C Link SDK Overview.Replace the device certificate information with the credentials of your test device.
Replace the value of mqtt_host with the MQTT ingest endpoint of the Enterprise instance where the device is located.
In the service list, add the configuration for the CUSTOM_SSH service. Do not delete the original _SSH service.
The following code shows the configuration.
/* TODO: Replace with your own device credentials */ char *product_key = "xxx"; char *device_name = "device2"; char *device_secret = "xxx"; /* ... */ char *mqtt_host = "xxx.mqtt.iothub.aliyuncs.com"; uint16_t port = 443; /* The destination port is 443 regardless of whether the device uses TLS to connect to Alibaba Cloud IoT Platform */ /* System adaptation functions located in the portfiles/aiot_port folder */ extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile; /* Server certificate located 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 = "CUSTOM_SSH", .ip = "127.0.0.1", .port = 22, } };Log on to the Linux virtual machine. Upload the modified SDK files from the previous step to the development environment on the Linux virtual machine.
In the SDK root directory `/LinkSDK`, run the
makecommand to compile the sample program. Then, run the sample file../output/remote-access-basic-demoCheck the operational logs. The following information indicates that the device is online and the secure tunnel SDK has started correctly.
After a successful run, the terminal output shows that the MQTT connection succeeded. The presence of
remote proxy thread start!andheartbeat responseindicates that the remote proxy thread has started and the heartbeat is normal.root@i-xxx:~/opt/LinkSDKRDP# ./output/remote-access-basic-demo [1646882104.155][LK-0313] MQTT user calls aiot_mqtt_connect api, connect [1646882104.155][LK-032A] mqtt host: xxx mqtt.iothub.aliyuncs.com [1646882104.155][LK-0317] user name: device2&xxx [1646882104.155][LK-0318] password: xxx establish tcp connection with server(host='xxx.mqtt.iothub.aliyuncs.com', port=[443]) success to establish tcp, fd=3 local port: 51094 [1646882104.166][LK-1000] establish mbedtls connection with server(host='xxx.mqtt.iothub.aliyuncs.com', port=[443]) [1646882104.233][LK-1000] success to establish mbedtls connection, (cost 45247 bytes in total, max used 47983 bytes) [1646882104.288][LK-0313] MQTT connect success in 123 ms AIOT_MQTTEVT_CONNECT [1646882104.288][LK-0309] sub: /sys/xxx/device2/secure_tunnel/notify [1646882104.288][LK-0309] sub: /sys/xxx/device2/secure_tunnel/proxy/request_reply [1646882104.288][LK-0309] pub: /sys/xxx/device2/secure_tunnel/proxy/request [LK-030A] > 7B 22 69 64 22 3A 31 30 30 30 2C 22 70 61 72 61 | {"id":1000,"para [LK-030A] > 6D 73 22 3A 7B 7D 7D | ms":{}} [1646882104.288][LK-1C80] remote proxy thread start! heartbeat responseLog on to the IoT Platform console. Go to the Enterprise instance page. In the navigation pane on the left, choose Device Management > Devices. Find the target device and confirm that its status is Online.
On the Device List page of the IoT Platform console, the device
device2shows an online status, with the last online time of 2022/03/10 11:15:04.271.
Create a secure tunnel
Follow these steps to create a secure tunnel for the target device in the IoT Platform console. You can also call the IoT Platform cloud API CreateDeviceTunnel to create a secure tunnel. For more information, see Server-side SDKs.
Log on to the IoT Platform console.
On the Instance Overview page, click the target Enterprise instance to go to the Instance Details page.
In the navigation pane on the left, choose Monitoring and O&M > Secure Tunnel.
On the Secure Tunnel page, click Create Secure Tunnel.
In the Create Tunnel dialog box, select the Product (for example, Smart Light) and Device (for example, device2), and then click Confirm. The dialog box displays a notice: A secure tunnel is valid for 24 hours by default after creation. After 24 hours, the status automatically changes to Closed, and a closed secure tunnel cannot be reopened.
In the dialog box that appears, click Copy All and save the tunnel ID, access-side token, and URL.
After the secure tunnel is created, the dialog box displays the access-side token and access-side URL (in the format
wss://iot-secure-tunnel-cn-<region-ID>....). Copy and save these items promptly, as they cannot be retrieved after the page is closed. The device access client uses this URL to establish a WebSocket connection and passes the token in the HTTP Request Header for authentication.After the secure tunnel is created, the device client receives a connection notification. The secure tunnel SDK uses the information in this notification to establish a WebSocket connection with IoT Platform. The following message is an example:
[1646882557.166][LK-0000] tunnel_switch_topic_handler payload:{"schema":"wss","path":"/tunnel/xxx xxx xxx/dest","token_expire":86399,"t ra_event_cb AIOT_RA_EVT_OPEN_WEBSOCKET [1646882557.322][LK-1C80] start to create cloud channel [1646882557.322][LK-1C80] 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=5 local port: 55528 [1646882557.333][LK-1000] establish mbedtls connection with server(host='iot-secure-tunnel-cn-sh.aliyuncs.com', port=[443]) [1646882557.399][LK-1000] success to establish mbedtls connection. (cost 55960 bytes in total, max used 58648 bytes) [1646882557.422][LK-0F10] open_cloud_proxy_channel success [1646882557.422][LK-1C80] websocket xxx xxx xxx: opened ra_event_cb AIOT_RA_EVT_CONNECT b083 [1646882566.688][LK-1C80] websocket xxx xxx xxx: pingOn the Secure Tunnel management page, the secure tunnel status for device device2 changes to Opened, the device client shows Connected, and the access client shows Not Connected, indicating that the device client has successfully connected.
Develop the access-side proxy service (Java)
Preparations
Download the sample code for the access-side proxy service. For more information, see alibabacloud-iot-java-demo.
Prepare the development environment. This topic uses a Java development environment with the following specifications:
Operating system: Windows 10 (64-bit)
JDK version: JDK 8 (or later)
Integrated development environment (IDE): IntelliJ IDEA Community Edition
Start the access-side proxy demo
Unzip the downloaded sample code package.
Open IntelliJ IDEA and import the unzipped sample project.
In the `SourceProxyStarter.java` file under `com.aliyun.iotx.lp.demo.secure.tunnel.source.proxy`, configure the tunnel ID, access-side token, and URL that you saved.
The `SourceProxyStarter` class of the access-side proxy uses `CUSTOM_SSH` as the default `ServiceType` and `6422` as the default port for the local proxy. This example uses the default configurations. For your own scenarios, you can modify the settings in the `SourceProxyStarter` class as needed.
public class SourceProxyStarter { private static volatile boolean hasStopped = false; public static void main(String[] args) throws JoranException, IOException, InterruptedException { load(SourceProxyStarter.class.getClassLoader().getResource("logback-spring.xml").getPath()); /** * please replace the following variables with the tunnel connection info */ String tunnelId = "xxx"; String sourceUri = "xxx"; String sourceToken = "xxx"; /** * please replace the portOfService variables with the service type supported by device */ Map<String, Integer> portOfService = new HashMap<>(); portOfService.put("CUSTOM_SSH", 6422);Run the `SourceProxyStarter.java` sample code. After the main program of the access-side proxy starts, it uses the configured connection information to establish a WebSocket connection with IoT Platform and waits for service access requests.
After running SourceProxyStarter, the console outputs the following log, indicating that the access-side proxy has started successfully:
13:43:24,033 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [console] to Logger[com.aliyun.iot.secure.tunnel] 13:43:24,033 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration. 13:43:24,033 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@6895a785 - Registering current configuration as safe fallback point 2022-03-10 13:43:29,696 [main] INFO com.aliyun.iot.secure.tunnel.protocol.source.TunnelSource - source connect success. 2022-03-10 13:43:29,701 [main] DEBUG com.aliyun.iot.secure.tunnel.source.proxy.DeviceTunnelSourceProxy - DeviceTunnelSourceProxy tunnel connected. tunnelId:xxx 2022-03-10 13:43:29,701 [main] INFO com.aliyun.iot.secure.tunnel.source.proxy.DeviceTunnelSourceProxy - DeviceTunnelSourceProxy listener start 2022-03-10 13:43:29,740 [main] INFO com.aliyun.iot.secure.tunnel.source.proxy.DeviceTunnelSourceProxy - DeviceTunnelSourceProxy listener channelId:d01b6009 2022-03-10 13:43:29,741 [main] INFO com.aliyun.iot.secure.tunnel.source.proxy.DeviceTunnelSourceProxy - DeviceTunnelSourceProxy listener channelId:e2100e8d 2022-03-10 13:43:29,741 [main] INFO com.aliyun.iot.secure.tunnel.source.proxy.DeviceTunnelSourceProxy - DeviceTunnelSourceProxy listener started 2022-03-10 13:43:29,741 [main] DEBUG com.aliyun.iot.secure.tunnel.source.proxy.DeviceTunnelSourceProxy - DeviceTunnelSourceProxy started. tunnelId:xxx 2022-03-10 13:43:30,711 [Thread-0] DEBUG com.aliyun.iot.secure.tunnel.protocol.source.TunnelSource - tunnel source send ping frame. 2022-03-10 13:43:36,724 [Thread-0] DEBUG com.aliyun.iot.secure.tunnel.protocol.source.TunnelSource - tunnel source send ping frame. 2022-03-10 13:43:42,724 [Thread-0] DEBUG com.aliyun.iot.secure.tunnel.protocol.source.TunnelSource - tunnel source send ping frame.
Develop the access-side proxy service (Go)
Preparations
Download the sample code for the access-side proxy service. For more information, see alibabacloud-iot-go-demo.
Install the Go development environment. You can obtain it from the official Go website.
NoteTo compile and run the Go sample code, you also need GCC. Install GCC on your local system.
Start the access-side proxy demo
Unzip the downloaded sample code package.
Use your Go development environment to compile and run the `/src/aliyun.com/iot/securetunnel/main.go` file to start the agent program.
After the agent program starts, a proxy software window appears. Enter the device secure tunnel information that you saved.
In the proxy software, the default ServiceType is `CUSTOM_SSH`, and the default LocalProxyPort is `6421`. This example uses the default ServiceType and changes the LocalProxyPort to `6422`. For your own scenarios, you can modify these settings as needed.
Ensure that the ServiceType is configured in the device-side SDK. The LocalProxyPort must be an unused local port.
In the proxy software interface, click start. After the main program of the access-side proxy starts, it uses the configured access-side connection information to establish a WebSocket connection with IoT Platform and waits for service access requests. The operational log is as follows:
>go run main.go conInfo:{"token":"xxx","url":"wss://iot-secure-tunnel-cn-sh.aliyuncs.com/tunnel/xxx/source"} serviceType:CUSTOM_SSH port:6422 connecting to wss://iot-secure-tunnel-cn-sh.aliyuncs.com:443/tunnel/xxx /source sourceProxy.SecureTunnel connection status:true tunnel : xxx source proxy started successfully. send ping frame success send ping frame success
You can use the packaging feature of Go to generate an executable program for your operating system. This simplifies future use and distribution to other users.
Remotely access the device through the local proxy
After the access-side agent program starts successfully, you can remotely access the device as follows.
This example shows how to use SSH to connect from a Windows 10 (64-bit) system to a Linux device. Open a local Command Prompt window, enter the command ssh root@localhost -p 6422, and press Enter to log on to the device. The results are as follows:
Logon in the Command Prompt window:
ssh root@localhost -p 6422 The authenticity of host '[localhost]:6422 ([::1]:6422)' can't be established. ECDSA key fingerprint is SHA256:xxx3Q. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added '[localhost]:6422' (ECDSA) to the list of known hosts. root@localhost's password: Welcome to Ubuntu 16.04.7 LTS (GNU/Linux 4.4.0-210-generic x86_64) * Documentation: https://help.ubuntu.com * Management: https://landscape.canonical.com * Support: https://ubuntu.com/advantage New release '18.04.6 LTS' available. Run 'do-release-upgrade' to upgrade to it. Welcome to Alibaba Cloud Elastic Compute Service ! Last login: Thu Mar 10 15:16:50 2022 from xxx root@xxx: #Connection request logs on the server-side:
Java
2022-03-10 15:24:28,421 [Thread-0] DEBUG com.aliyun.iot.secure.tunnel.protocol.source.TunnelSource - tunnel source send ping frame. 2022-03-10 15:24:28,588 [nioEventLoopGroup-4-1] INFO com.aliyun.iot.secure.tunnel.protocol.source.TunnelSource - SourceSimulator sendSessionCreateFrame header: {"service_type":"CUSTOM_SSH","frame_type":"SESSION_CREATE","frame_id:6089} 2022-03-10 15:24:28,705 [nioEventLoopGroup-2-1] INFO com.aliyun.iot.secure.tunnel.protocol.handler.ReceivedTunnelFrameProcessor - receive success response, messageHeader={"service_type":"CUSTOM_SSH","session_id":"164689691064466","frame_type":"COMMON_RESPONSE","frame_id:6089}; response={"code":0,"msg":"new session response","success":true} 2022-03-10 15:24:28,705 [nioEventLoopGroup-2-1] INFO com.aliyun.iot.secure.tunnel.protocol.source.TunnelSource - source create session success. sessionId:164689691064466 2022-03-10 15:24:28,849 [nioEventLoopGroup-2-1] DEBUG com.aliyun.iot.secure.tunnel.protocol.handler.ReceivedTunnelFrameProcessor - source receive data-trans-frameGo
xxx send ping frame success xxx tunnel:xxx received tunnelFrame:header:FrameId:253921263
Response logs on the device-side:
[1652842219.233][LK-1C80] new session session_id: xxx, type CUSTOM_SSH local 127.0.0.1, 22 establish tcp connection with server(host='127.0.0.1', port=[22]) success to establish tcp, fd=6 local port: 49678 [1652842219.233][LK-1C80] response payload:{"code":0,"msg":"new session response"} [1652842219.233][LK-1C80] response header:{"frame_type":1,"frame_id":xxx,"session_id":"xxx"}