Skip to main content

Connect through telnet on two different computers using Relay Hybrid Connection - Azure Relay

A few days ago I wrote a short post about Relay Hybrid Connection (using Azure Relay), that enable us to establish a secure tunnel connection between two different computers, that can be located anywhere in the world.
The connection is done over HTTPS using web sockets. This means that even if you have firewalls, as long as port 443 is open, you can have a secure connection out of the box.
A short description of Relay Hybrid Connection can be found in the previous post Secure tunnel using Hybrid Connections.

Scope
In today post let's see how we can establish a Telnet connection between two different computers using Relay Hybrid Connection and Node.JS.

Why Telnet?
I decided to make this sample using Telnet, because a connection through Telnet requires a direct connection to a specific port. Having such a connection requires as to redirect content that is send to a a port directly to Azure Relay.
If we can do such a thing, than we can redirect the VNC or RDP port without a problem.

What we need ?
From Azure Relay perspective we need to create a Relay Hybrid Connection. This can be done easily from Azure Portal (see Azure documentation for this). On top of it, we need to write code that redirects traffic from a local port to a web-socket. Once we manage to do this, we only need to configure the web-socket client to connect to our Relay Hybrid Connection.
Two Node.js packages are required (that can be downloaded from NPM):
  • net - It is used to create the socket for the local ports
  • hyco-ws - Wrapper over web-sockets, that helps us to connect to Azure Relay. It is not mandatory, but it is more simple for example to create the connection URL automatically and not manually
You will see later on, that there is an implementation for Server and Client. For such a connection (over web-sockets), it is required that one computer (computer A) to play the role of listener (server). Another computer needs to play the role of client (computer B).
This is because of how web-sockets works and the role of client and server can be switched between computer A and B.

Server implementation (computer A)
In this sample the computer A connects on port 1235. We will need to create a socket that listen on this port.
net.createServer(function(localsocket)
{

}.listen(1235);

Once we done this, we need to create a web-socket connection to our Azure Relay and play the role of the web-socket server (listen to relay server). In the same time when we create this connection, we'll need to register to the event that is trigger when new data is send from Azure Relay. This content needs to be directed to local socket, from where it will be pushed to port 1235.
var wss = websocket.createRelayedServer({
        ...
    }, 
    function (socket) {
        relaysocket = socket;
        relaysocket.onmessage = function (event) {
            // Send data to local socket (local port)
            localsocket.write(event.data);
        };      
        
        relaysocket.send(d);
    });

The last thing is to register to the local socket event that is triggered when new data is send from local computer to our port. Data needs to be redirected to our web socket.
localsocket.on('data', function(d) {
        // Receive data on local socket, redirect it to relay server (web socket)         
        relaysocket.send(d);
    });
And we are done with the server.

Client implementation (computer B)
On computer B, we will use port 1234 as local port. I decided to not use the same port, because in this way we can test our solution using only one computer.
From the implementation perspective, the code is similar. The main difference is the order on what we open and connect first. For the server, we first create the connection to the local socket and only after it we connected to Azure Relay.
In the case of the client, we first need to connect to relay and only after it to connect to the socket. Below you can find the implementation of the client.
client.js
const net = require('net');
const webrelay = require('hyco-ws');

// Relay information
const ns = "rvrelay.servicebus.windows.net";
const path = "a";
const keyrule = "full";
const key = "hdm88wZHtAj412uqSV7IRscJiBKnFcWs3Sw5UFtWQ/o=";

// Local port used to send data
var sourceport = 1234;
var localsocket;
// Create relay connection for client
var relayclient = webrelay.relayedConnect(
        webrelay.createRelaySendUri(ns, path),
        webrelay.createRelayToken('http://'+ns, keyrule, key),
        function (socket) {
            console.log("Connected to relay")
            // Send msg to relay that confirms that cnnection was with success. 
            socket.send("Connection with success")

            // Define action for content received from relay
            relayclient.onmessage = function (event) {
                console.log('Data from relay: ' + event.data);
                // Send data to local socket (port)
                localsocket.write(event.data);
            };

            // Create local socket to the given port                     
            net.createServer(function(socket)
            {
                localsocket = socket;
                localsocket.on('data', function(d) {
                    // Send data from socket to 
                    relayclient.send(d);
                });
                }).listen(sourceport);            
        }
    ); 

As you can see the client and server implementation are very similar. The magic is happening behind the scene on Azure Relay that now supports web sockets.
The server implementation source code can be found at the end of this post.

Running the sample
All source code can be found on Github - https://github.com/vunvulear/Stuff/tree/master/Azure/relay-hybrid-connections-telnet2telnet
Steps:
  1. Update the Azure Relay connection information
  2. If needed, change the port of the client and server
  3. Check that you have Ttelnet installed (if not click here)
  4. Check that you have Node.Js installed (if not click here)
  5. [on server] Open power-shell and run server ('node server.js')
  6. [on server] Open power-shell and run telnet where you need to enter 'localhost 1235'
  7. [on client] Open power-shell and run client ('node client.js')
  8. [on client] Open power-shell and run telnet where you need to enter 'localhost 1234'
  9. And you are done, you have a secure tunnel connection between them. Feel free to write anything in the telnet consoles. The content will be visible in the other telnet window.
Security  
From a security point of view we shall take into consideration two things. 
At transport level, we are connected over a secure connection to Azure Relay (HTTPS/Web Socket). It means the connection is secure and people will not be able to access and see the content that we send through the wire.
At connection level, Azure Relay is using SAS (Shared Access Signatures), that allows us to specify what kind of operation can be done on a specific Azure Relay and for what period of time. It means that without a valid SAS you cannot connect to a relay.

Conclusion
I'm exited to see that we can establish a secure connection, very similar to a VNC connection) between two computers that are in different networks using an out of the box Azure Service. More exciting is that this connection is done over web-sockets, meaning that I can connect from any kind of system and I can use any kind of technology stack (C++, C#, Node.JS, Java, Ruby, Go and so on). 

In the next posts we will see how we can establish a VNC client connectin using Azure Relay and Relay Hybrid Connection. 
Github source code: https://github.com/vunvulear/Stuff/tree/master/Azure/relay-hybrid-connections-telnet2telnet

server.js
const net = require('net');
const websocket = require('hyco-ws');


// Relay information
const ns = "rvrelay.servicebus.windows.net";
const path = "a";
const keyrule = "full";
const key = "hdm88wZHtAj412uqSV7IRscJiBKnFcWs3Sw5UFtWQ/o=";

// Local port where content is redirected (to/from)
var localport = 1235; 
var relaysocket;        
// Create local  socket connection
net.createServer(function(localsocket)
{
    // write to socket a dummy connection
    localsocket.write("Connection with success");
    localsocket.on('data', function(d) {
        // Receive data on local socket, redirect it to relay server (web socket)         
        relaysocket.send(d);
    });

    // Create relay server, only after local socket was open
    var wss = websocket.createRelayedServer(
        {
            // Init listener to relay
            server : websocket.createRelayListenUri(ns, path),
            token: websocket.createRelayToken('http://' + ns, keyrule, key)
        }, 
        function (socket) {
            relaysocket = socket;
            console.log('New connection from client');
            relaysocket.onmessage = function (event) {
                // Send data to local socket (local port)
                localsocket.write(event.data);
                console.log("Send data to local port: " + event.data);
            };
            relaysocket.on('close', function () {
                console.log('Relay connectin was closed');
            });       
        });

        console.log('Ready for new connection');

        wss.on('error', function(err) {
        console.log('error' + err);
        });

        websocket.createRelayListenUri() 

}).listen(localport);

Comments

Popular posts from this blog

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(...

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine: threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration: TeamCity .NET 4.51 EF 6.0.2 VS2013 It see...

Navigating Cloud Strategy after Azure Central US Region Outage

 Looking back, July 19, 2024, was challenging for customers using Microsoft Azure or Windows machines. Two major outages affected customers using CrowdStrike Falcon or Microsoft Azure computation resources in the Central US. These two outages affected many people and put many businesses on pause for a few hours or even days. The overlap of these two issues was a nightmare for travellers. In addition to blue screens in the airport terminals, they could not get additional information from the airport website, airline personnel, or the support line because they were affected by the outage in the Central US region or the CrowdStrike outage.   But what happened in reality? A faulty CrowdStrike update affected Windows computers globally, from airports and healthcare to small businesses, affecting over 8.5m computers. Even if the Falson Sensor software defect was identified and a fix deployed shortly after, the recovery took longer. In parallel with CrowdStrike, Microsoft provi...