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

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Can User Technical Profile Influence AI Architecture Decisions?

In the last few days, I ran a small experiment on Devin/Windsurf/Cascade, BMAD, and LLM-based architecture decisions. The initial concern was simple: if an AI coding assistant knows something about the user, for example, that the user is a Java developer or a .NET developer, can this information influence the architecture and technology stack that the AI will propose? This question is important because many companies are starting to use AI tools not only for coding but also for product discovery, architecture, documentation, and technical decision-making. If the AI is influenced by the developer's personal profile, the result may not be fully neutral. It may look like a business or architecture decision, but in reality, it may be partially shaped by the context of the person using the tool. The test was done using BMAD with Devin/Windsurf/Cascade. The scenario was a unified field service operations platform. The task was to let BMAD refine the product, define the architecture and s...

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...