Added SSH support in terminal tab for local devices.

This commit is contained in:
Ylian Saint-Hilaire 2021-05-08 18:09:49 -07:00
parent e44ed5be4f
commit 9b85a51f67
6 changed files with 273 additions and 19 deletions

View File

@ -229,6 +229,7 @@ module.exports.CreateSshRelay = function (parent, db, ws, req, args, domain) {
// Decode the authentication cookie
obj.cookie = parent.parent.decodeCookie(req.query.auth, parent.parent.loginCookieEncryptionKey);
if (obj.cookie == null) { obj.ws.send(JSON.stringify({ action: 'sessionerror' })); obj.close(); return; }
console.log(obj.cookie);
// Start the looppback server
function startRelayConnection() {
@ -258,7 +259,7 @@ module.exports.CreateSshRelay = function (parent, db, ws, req, args, domain) {
obj.sshShell = stream;
obj.sshShell.setWindow(obj.termSize.rows, obj.termSize.cols, obj.termSize.height, obj.termSize.width);
obj.sshShell.on('close', function () { obj.close(); });
obj.sshShell.on('data', function (data) { obj.ws.send('~' + data); });
obj.sshShell.on('data', function (data) { obj.ws.send('~' + data.toString()); });
});
obj.ws.send(JSON.stringify({ action: 'connected' }));
});
@ -301,6 +302,7 @@ module.exports.CreateSshRelay = function (parent, db, ws, req, args, domain) {
if (typeof msg.action != 'string') return;
switch (msg.action) {
case 'connect': {
// TODO: Verify inputs
obj.termSize = msg;
obj.username = msg.username;
obj.password = msg.password;
@ -327,4 +329,200 @@ module.exports.CreateSshRelay = function (parent, db, ws, req, args, domain) {
ws.on('close', function (req) { parent.parent.debug('relay', 'SSH: Browser websocket closed'); obj.close(); });
return obj;
};
};
// Construct a SSH Terminal Relay object, called upon connection
module.exports.CreateSshTerminalRelay = function (parent, db, ws, req, domain, user, cookie, args) {
const Net = require('net');
const WebSocket = require('ws');
// SerialTunnel object is used to embed SSH within another connection.
function SerialTunnel(options) {
var obj = new require('stream').Duplex(options);
obj.forwardwrite = null;
obj.updateBuffer = function (chunk) { this.push(chunk); };
obj._write = function (chunk, encoding, callback) { if (obj.forwardwrite != null) { obj.forwardwrite(chunk); } if (callback) callback(); }; // Pass data written to forward
obj._read = function (size) { }; // Push nothing, anything to read should be pushed from updateBuffer()
obj.destroy = function () { delete obj.forwardwrite; }
return obj;
}
const obj = {};
obj.ws = ws;
obj.relayActive = false;
parent.parent.debug('relay', 'SSH: Request for SSH relay (' + req.clientIp + ')');
// Disconnect
obj.close = function (arg) {
if (obj.ws == null) return;
// Collect how many raw bytes where received and sent.
// We sum both the websocket and TCP client in this case.
//var inTraffc = obj.ws._socket.bytesRead, outTraffc = obj.ws._socket.bytesWritten;
//if (obj.wsClient != null) { inTraffc += obj.wsClient._socket.bytesRead; outTraffc += obj.wsClient._socket.bytesWritten; }
//console.log('WinSSH - in', inTraffc, 'out', outTraffc);
if (obj.sshShell) {
obj.sshShell.destroy();
obj.sshShell.removeAllListeners('data');
obj.sshShell.removeAllListeners('close');
try { obj.sshShell.end(); } catch (ex) { console.log(ex); }
delete obj.sshShell;
}
if (obj.sshClient) {
obj.sshClient.destroy();
obj.sshClient.removeAllListeners('ready');
try { obj.sshClient.end(); } catch (ex) { console.log(ex); }
delete obj.sshClient;
}
if (obj.wsClient) {
obj.wsClient.removeAllListeners('open');
obj.wsClient.removeAllListeners('message');
obj.wsClient.removeAllListeners('close');
try { obj.wsClient.close(); } catch (ex) { console.log(ex); }
delete obj.wsClient;
}
if ((arg == 1) || (arg == null)) { try { ws.close(); } catch (e) { console.log(e); } } // Soft close, close the websocket
if (arg == 2) { try { ws._socket._parent.end(); } catch (e) { console.log(e); } } // Hard close, close the TCP socket
obj.ws.removeAllListeners();
obj.relayActive = false;
delete obj.termSize;
delete obj.cookie;
delete obj.ws;
};
// Start the looppback server
function startRelayConnection(authCookie) {
try {
// Setup the correct URL with domain and use TLS only if needed.
var options = { rejectUnauthorized: false };
if (domain.dns != null) { options.servername = domain.dns; }
var protocol = 'wss';
if (args.tlsoffload) { protocol = 'ws'; }
var domainadd = '';
if ((domain.dns == null) && (domain.id != '')) { domainadd = domain.id + '/' }
var url = protocol + '://127.0.0.1:' + args.port + '/' + domainadd + ((obj.mtype == 3) ? 'local' : 'mesh') + 'relay.ashx?noping=1&p=11&auth=' + authCookie // Protocol 11 is Web-SSH
parent.parent.debug('relay', 'SSH: Connection websocket to ' + url);
obj.wsClient = new WebSocket(url, options);
obj.wsClient.on('open', function () { parent.parent.debug('relay', 'SSH: Relay websocket open'); });
obj.wsClient.on('message', function (data) { // Make sure to handle flow control.
if ((obj.relayActive == false) && (data == 'c')) {
obj.relayActive = true;
// Create a serial tunnel && SSH module
obj.ser = new SerialTunnel();
const Client = require('ssh2').Client;
obj.sshClient = new Client();
obj.sshClient.on('ready', function () { // Authentication was successful.
obj.sshClient.shell(function (err, stream) { // Start a remote shell
if (err) { obj.close(); return; }
obj.sshShell = stream;
obj.sshShell.setWindow(obj.termSize.rows, obj.termSize.cols, obj.termSize.height, obj.termSize.width);
obj.sshShell.on('close', function () { obj.close(); });
obj.sshShell.on('data', function (data) { obj.ws.send('~' + data.toString()); });
});
obj.ws.send('c');
});
obj.sshClient.on('error', function (err) {
if (err.level == 'client-authentication') { obj.ws.send(JSON.stringify({ action: 'autherror' })); }
obj.close();
});
// Setup the serial tunnel, SSH ---> Relay WS
obj.ser.forwardwrite = function (data) { if ((data.length > 0) && (obj.wsClient != null)) { try { obj.wsClient.send(data); } catch (ex) { } } };
// Connect the SSH module to the serial tunnel
var connectionOptions = { sock: obj.ser }
if (typeof obj.username == 'string') { connectionOptions.username = obj.username; delete obj.username; }
if (typeof obj.password == 'string') { connectionOptions.password = obj.password; delete obj.password; }
obj.sshClient.connect(connectionOptions);
// We are all set, start receiving data
ws._socket.resume();
} else {
// Relay WS --> SSH
if ((data.length > 0) && (obj.ser != null)) { try { obj.ser.updateBuffer(data); } catch (ex) { console.log(ex); } }
}
});
obj.wsClient.on('close', function () { parent.parent.debug('relay', 'SSH: Relay websocket closed'); obj.close(); });
obj.wsClient.on('error', function (err) { parent.parent.debug('relay', 'SSH: Relay websocket error: ' + err); obj.close(); });
} catch (ex) {
console.log(ex);
}
}
// When data is received from the web socket
// SSH default port is 22
ws.on('message', function (msg) {
try {
if (typeof msg != 'string') return;
if (msg[0] == '{') {
// Control data
msg = JSON.parse(msg);
if (typeof msg.action != 'string') return;
switch (msg.action) {
case 'sshauth': {
// TODO: Verify inputs
obj.termSize = msg;
obj.username = msg.username;
obj.password = msg.password;
// Create a mesh relay authentication cookie
var cookieContent = { userid: user._id, domainid: user.domain, nodeid: obj.nodeid, tcpport: obj.tcpport };
if (obj.mtype == 3) { cookieContent.lc = 1; } // This is a local device
startRelayConnection(parent.parent.encodeCookie(cookieContent, parent.parent.loginCookieEncryptionKey));
break;
}
case 'resize': {
obj.termSize = msg;
if (obj.sshShell != null) { obj.sshShell.setWindow(obj.termSize.rows, obj.termSize.cols, obj.termSize.height, obj.termSize.width); }
break;
}
}
} else if (msg[0] == '~') {
// Terminal data
if (obj.sshShell != null) { obj.sshShell.write(msg.substring(1)); }
}
} catch (ex) { obj.close(); }
});
// If error, do nothing
ws.on('error', function (err) { parent.parent.debug('relay', 'SSH: Browser websocket error: ' + err); obj.close(); });
// If the web socket is closed
ws.on('close', function (req) { parent.parent.debug('relay', 'SSH: Browser websocket closed'); obj.close(); });
// Decode the authentication cookie
var userCookie = parent.parent.decodeCookie(req.query.auth, parent.parent.loginCookieEncryptionKey);
if ((userCookie == null) || (userCookie.a != null)) { obj.close(); return; } // Invalid cookie
// Fetch the user
var user = parent.users[userCookie.userid]
if (user == null) { obj.close(); return; } // Invalid userid
// Check that we have a nodeid
if (req.query.nodeid == null) { obj.close(); return; } // Invalid nodeid
parent.GetNodeWithRights(domain, user, req.query.nodeid, function (node, rights, visible) {
// Check permissions
if ((rights & 8) == 0) { obj.close(); return; } // No MESHRIGHT_REMOTECONTROL rights
if ((rights != 0xFFFFFFFF) && (rights & 0x00000200)) { obj.close(); return; } // MESHRIGHT_NOTERMINAL is set
obj.mtype = node.mtype; // Store the device group type
obj.nodeid = node._id; // Store the NodeID
// Check the SSH port
obj.tcpport = 22;
if (typeof node.sshport == 'number') { obj.tcpport = node.sshport; }
// We are all set, start receiving data
ws._socket.resume();
// Send a request for SSH authentication
try { ws.send(JSON.stringify({ action:'sshauth' })) } catch (ex) { }
});
return obj;
};

View File

@ -150,7 +150,7 @@
connect : function (ip, domain, username, password, next) {
// Start connection
var self = this;
this.socket = new WebSocket('wss://' + window.location.host + '/mstsc/relay.ashx');
this.socket = new WebSocket('wss://' + window.location.host + '/mstscrelay.ashx');
this.socket.binaryType = 'arraybuffer';
this.socket.onopen = function () {
//console.log("WS-OPEN");

View File

@ -28,6 +28,7 @@ var CreateAgentRedirect = function (meshserver, module, serverPublicNamePort, au
obj.webrtc = null;
obj.debugmode = 0;
obj.serverIsRecording = false;
obj.urlname = 'meshrelay.ashx';
obj.latency = { lastSend: null, current: -1, callback: null };
if (domainUrl == null) { domainUrl = '/'; }
@ -43,7 +44,7 @@ var CreateAgentRedirect = function (meshserver, module, serverPublicNamePort, au
//obj.debug = function (msg) { console.log(msg); }
obj.Start = function (nodeid) {
var url2, url = window.location.protocol.replace('http', 'ws') + '//' + window.location.host + window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) + '/meshrelay.ashx?browser=1&p=' + obj.protocol + (nodeid?('&nodeid=' + nodeid):'') + '&id=' + obj.tunnelid;
var url2, url = window.location.protocol.replace('http', 'ws') + '//' + window.location.host + window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')) + '/' + obj.urlname + '?browser=1&p=' + obj.protocol + (nodeid?('&nodeid=' + nodeid):'') + '&id=' + obj.tunnelid;
//if (serverPublicNamePort) { url2 = window.location.protocol.replace('http', 'ws') + '//' + serverPublicNamePort + '/meshrelay.ashx?id=' + obj.tunnelid; } else { url2 = url; }
if ((authCookie != null) && (authCookie != '')) { url += '&auth=' + authCookie; }
if ((urlargs != null) && (urlargs.slowrelay != null)) { url += '&slowrelay=' + urlargs.slowrelay; }
@ -170,7 +171,7 @@ var CreateAgentRedirect = function (meshserver, module, serverPublicNamePort, au
// Control messages, most likely WebRTC setup
//console.log('New data', e.data.byteLength);
if (typeof e.data == 'string') {
obj.xxOnControlCommand(e.data);
if (e.data[0] == '~') { obj.m.ProcessData(e.data); } else { obj.xxOnControlCommand(e.data); }
} else {
// Send the data to the module
if (obj.m.ProcessBinaryCommand) {

View File

@ -6265,7 +6265,11 @@
}
// Attribute: Mesh Agent
if ((node.agent != null) && (node.agent.id != null) && (node.agent.ver != null)) {
if ((node.agent != null) && (node.agent.id != null) && (mesh.mtype == 3)) {
if (node.agent.id == 4) { x += addDeviceAttribute("Device Type", "Windows"); }
if (node.agent.id == 6) { x += addDeviceAttribute("Device Type", "Linux"); }
if (node.agent.id == 29) { x += addDeviceAttribute("Device Type", "macOS"); }
} else if ((node.agent != null) && (node.agent.id != null) && (node.agent.ver != null)) {
var str = '';
if (node.agent.id <= agentsStr.length) { str = agentsStr[node.agent.id]; } else { str = agentsStr[0]; }
if (node.agent.ver != 0) { str += ' v' + node.agent.ver; }
@ -6549,6 +6553,9 @@
var consoleRights = ((meshrights & 16) != 0);
if (consoleRights) { setupConsole(); } else { if (panel == 15) { panel = 10; } }
// If we are looking at a local non-windows device, enable terminal capability.
if ((mesh.mtype == 3) && (node.agent != null) && (node.agent.id > 4)) { node.agent.caps = 2; }
// Show or hide the tabs
// mesh.mtype: 1 = Intel AMT only, 2 = Mesh Agent, 3 = Local Device
// node.agent.caps (bitmask): 1 = Desktop, 2 = Terminal, 4 = Files, 8 = Console
@ -8541,13 +8548,12 @@
// Show and enable the right buttons
function updateTerminalButtons() {
var mtype = (currentNode.agent == 1) ? 1 : 2;
var termState = ((terminal != null) && (terminal.state != 0));
// Show the right buttons
QV('disconnectbutton2span', (termState == true));
QV('connectbutton2span', (termState == false) && (currentNode.agent != null) && (currentNode.agent.caps & 2));
if (mtype == 1) {
if (currentNode.mtype == 1) {
QV('connectbutton2hspan', (termState == false) && (terminalNode.intelamt != null) && (terminalNode.intelamt.state == 2));
QV('terminalSizeDropDown', (termState == false) && (terminalNode.intelamt != null) && (terminalNode.intelamt.state == 2));
} else {
@ -8555,8 +8561,11 @@
QV('terminalSizeDropDown', (termState == false) && (terminalNode.intelamt != null) && (terminalNode.intelamt.state == 2) && (terminalNode.intelamt.ver != null));
}
// Enable action button if mesh type is not "local devices"
QV('termActionsBtn', currentNode.mtype != 3);
// Enable buttons
var online = ((terminalNode.conn & 1) != 0); // If Agent (1) connected, enable Terminal
var online = ((terminalNode.conn & 1) != 0) || (currentNode.mtype == 3); // If Agent (1) connected, enable Terminal
QE('connectbutton2', online);
var hwonline = ((terminalNode.conn & 6) != 0); // If CIRA (2) or AMT (4) connected, enable hardware terminal
QE('connectbutton2h', hwonline);
@ -8640,12 +8649,40 @@
return obj;
}
function tunnelUpdate(data) { if (typeof data == 'string') { xterm.writeUtf8(data); } else { xterm.writeUtf8(new Uint8Array(data)); } }
function tunnelUpdate(data) {
if (typeof data == 'string') { xterm.writeUtf8(data); } else { xterm.writeUtf8(new Uint8Array(data)); }
}
function sshTunnelUpdate(data) {
if (typeof data == 'string') {
if (data[0] == '{') {
var j = JSON.parse(data);
switch (j.action) {
case 'sshauth': {
var x = '';
x += addHtmlValue("Username", '<input id=dp2user style=width:230px maxlength=64 autocomplete=off onkeyup=sshAuthKeyUp(event) />');
x += addHtmlValue("Password", '<input type=password id=dp2pass style=width:230px maxlength=64 autocomplete=off onkeyup=sshAuthKeyUp(event) />');
setDialogMode(2, "Authentication", 3, sshConnectEx, x);
setTimeout(sshAuthKeyUp, 50);
}
}
} else if (data[0] == '~') { xterm.writeUtf8(data.substring(1)); }
}
}
function sshAuthKeyUp(e) { QE('idx_dlgOkButton', (Q('dp2user').value.length > 0) && (Q('dp2pass').value.length > 0)); }
function sshConnectEx() { terminal.socket.send(JSON.stringify({ action: 'sshauth', username: Q('dp2user').value, password: Q('dp2pass').value, cols: xterm.cols, rows: xterm.rows, width: Q('termarea3xdiv').offsetWidth, height: Q('termarea3xdiv').offsetHeight })); }
// Send the new terminal size to the agent
function xTermSendResize() {
xtermResizeTimer = null;
if ((xterm != null) && (terminal != null) && (terminal.sendCtrlMsg != null)) { terminal.sendCtrlMsg(JSON.stringify({ ctrlChannel: '102938', type: 'termsize', cols: xterm.cols, rows: xterm.rows })); }
if ((xterm != null) && (terminal != null) && (terminal.sendCtrlMsg != null)) {
if (terminal.urlname == 'sshterminalrelay.ashx') {
terminal.socket.send(JSON.stringify({ action: 'resize', cols: xterm.cols, rows: xterm.rows, width: Q('termarea3xdiv').offsetWidth, height: Q('termarea3xdiv').offsetHeight }));
} else {
terminal.sendCtrlMsg(JSON.stringify({ ctrlChannel: '102938', type: 'termsize', cols: xterm.cols, rows: xterm.rows }));
}
}
}
function connectTerminal(e, contype, options) {
@ -8714,7 +8751,7 @@
xterm = new Terminal();
if (xtermfit) { xterm.loadAddon(xtermfit); }
xterm.open(Q('termarea3xdiv')); // termarea3x
xterm.onData(function (data) { if (terminal != null) { terminal.sendText(data); } })
xterm.onData(function (data) { if (terminal != null) { if (terminal.urlname == 'sshterminalrelay.ashx') { terminal.socket.send('~' + data); } else { terminal.sendText(data); } } })
if (xtermfit) { xtermfit.fit(); }
xterm.onTitleChange(function (title) { QH('termtitle', ' - ' + EscapeHtml(title)); });
xterm.onResize(function (size) {
@ -8724,7 +8761,8 @@
});
// Setup a terminal tunnel to the agent
terminal = CreateAgentRedirect(meshserver, CreateRemoteTunnel(tunnelUpdate, termoptions), serverPublicNamePort, authCookie, authRelayCookie, domainUrl);
terminal = CreateAgentRedirect(meshserver, CreateRemoteTunnel((currentNode.mtype == 3)? sshTunnelUpdate : tunnelUpdate, termoptions), serverPublicNamePort, authCookie, authRelayCookie, domainUrl);
if (currentNode.mtype == 3) { terminal.urlname = 'sshterminalrelay.ashx'; } // If this is a SSH session, change the URL to the SSH application relay.
terminal.debugmode = debugmode;
terminal.m.debugmode = debugmode;
terminal.options = termoptions;
@ -8808,7 +8846,10 @@
function termSendKey(key, id) {
if (!terminal || xxdialogMode) return;
if (xterm != null) {
if (terminal.sendText) {
if (terminal.urlname == 'sshterminalrelay.ashx') {
// SSH
terminal.socket.send('~' + String.fromCharCode(key));
} else if (terminal.sendText) {
// MeshAgent
terminal.sendText(String.fromCharCode(key));
} else {
@ -8837,9 +8878,16 @@
// Send special key
function sendSpecialKey() {
if (xterm != null) {
terminal.sendText(String.fromCharCode(Q('specialkeylist').value));
if (terminal.urlname == 'sshterminalrelay.ashx') {
// SSH
terminal.socket.send('~' + String.fromCharCode(Q('specialkeylist').value));
} else {
// Agent terminal
terminal.sendText(String.fromCharCode(Q('specialkeylist').value));
}
xterm.focus();
} else if (terminal != null) {
// Legacy terminal
terminal.m.TermSendKey(Q('specialkeylist').value);
Q('specialkeylist').blur();
Q('specialkeylistinput').blur();

View File

@ -138,7 +138,7 @@
user = Q('dp2user').value;
pass = Q('dp2pass').value;
state = 1;
var url = window.location.protocol.replace('http', 'ws') + '//' + window.location.host + domainurl + 'ssh/relay.ashx?auth=' + cookie + (urlargs.key ? ('&key=' + urlargs.key) : '');
var url = window.location.protocol.replace('http', 'ws') + '//' + window.location.host + domainurl + 'sshrelay.ashx?auth=' + cookie + (urlargs.key ? ('&key=' + urlargs.key) : '');
socket = new WebSocket(url);
socket.onopen = function (e) {
state = 2;

View File

@ -1901,12 +1901,14 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
if ((obj.GetNodeRights(user, node.meshid, node._id) & MESHRIGHT_REMOTECONTROL) == 0) { res.sendStatus(401); return; }
// Figure out the target port
var port = 3389;
var port = 0;
if (page == 'ssh') {
// SSH port
port = 22;
if (typeof node.sshport == 'number') { port = node.sshport; }
} else {
// RDP port
port = 3389;
if (typeof node.rdpport == 'number') { port = node.rdpport; }
}
if (req.query.port != null) { var qport = 0; try { qport = parseInt(req.query.port); } catch (ex) { } if ((typeof qport == 'number') && (qport > 0) && (qport < 65536)) { port = qport; } }
@ -5553,7 +5555,7 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
// Setup MSTSC.js if needed
if (domain.mstsc === true) {
obj.app.get(url + 'mstsc.html', function (req, res) { handleMSTSCRequest(req, res, 'mstsc'); });
obj.app.ws(url + 'mstsc/relay.ashx', function (ws, req) {
obj.app.ws(url + 'mstscrelay.ashx', function (ws, req) {
const domain = getDomain(req);
if (domain == null) { parent.debug('web', 'mstsc: failed checks.'); try { ws.close(); } catch (e) { } return; }
require('./apprelays.js').CreateMstscRelay(obj, obj.db, ws, req, obj.args, domain);
@ -5563,13 +5565,18 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
// Setup SSH if needed
if (domain.ssh === true) {
obj.app.get(url + 'ssh.html', function (req, res) { handleMSTSCRequest(req, res, 'ssh'); });
obj.app.ws(url + 'ssh/relay.ashx', function (ws, req) {
obj.app.ws(url + 'sshrelay.ashx', function (ws, req) {
const domain = getDomain(req);
if (domain == null) { parent.debug('web', 'ssh: failed checks.'); try { ws.close(); } catch (e) { } return; }
try {
require('./apprelays.js').CreateSshRelay(obj, obj.db, ws, req, obj.args, domain);
} catch (ex) { console.log(ex); }
});
obj.app.ws(url + 'sshterminalrelay.ashx', function (ws, req) {
PerformWSSessionAuth(ws, req, true, function (ws1, req1, domain, user, cookie) {
require('./apprelays.js').CreateSshTerminalRelay(obj, obj.db, ws1, req1, domain, user, cookie, obj.args);
});
});
}
// Setup firebase push only server