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(

Azure AD and AWS Cognito side-by-side

In the last few weeks, I was involved in multiple opportunities on Microsoft Azure and Amazon, where we had to analyse AWS Cognito, Azure AD and other solutions that are available on the market. I decided to consolidate in one post all features and differences that I identified for both of them that we should need to take into account. Take into account that Azure AD is an identity and access management services well integrated with Microsoft stack. In comparison, AWS Cognito is just a user sign-up, sign-in and access control and nothing more. The focus is not on the main features, is more on small things that can make a difference when you want to decide where we want to store and manage our users.  This information might be useful in the future when we need to decide where we want to keep and manage our users.  Feature Azure AD (B2C, B2C) AWS Cognito Access token lifetime Default 1h – the value is configurable 1h – cannot be modified

What to do when you hit the throughput limits of Azure Storage (Blobs)

In this post we will talk about how we can detect when we hit a throughput limit of Azure Storage and what we can do in that moment. Context If we take a look on Scalability Targets of Azure Storage ( https://azure.microsoft.com/en-us/documentation/articles/storage-scalability-targets/ ) we will observe that the limits are prety high. But, based on our business logic we can end up at this limits. If you create a system that is hitted by a high number of device, you can hit easily the total number of requests rate that can be done on a Storage Account. This limits on Azure is 20.000 IOPS (entities or messages per second) where (and this is very important) the size of the request is 1KB. Normally, if you make a load tests where 20.000 clients will hit different blobs storages from the same Azure Storage Account, this limits can be reached. How we can detect this problem? From client, we can detect that this limits was reached based on the HTTP error code that is returned by HTTP