-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
350 lines (312 loc) · 9.12 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// vim: set ts=4 sw=4:
/*jshint esversion: 6 */
/*
Copyright (C) 2015-2024 Lars Windolf <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
const http = require('http'),
express = require('express'),
cors = require('cors'),
os = require('os'),
fs = require('fs'),
app = express(),
StatefulProcessCommandProxy = require("stateful-process-command-proxy"),
WebSocket = require('ws');
const { exec } = require("child_process");
var config = require(os.homedir() + '/.config/wurmterm/config.json');
var probes = require('./probes/default.json');
var proxies = {};
var filters = {};
process.title = 'WurmTermBackend';
process.on('uncaughtException', function (err) {
// dirty catch of broken SSH pipes
console.log(err.stack);
});
// Hostname matching based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address
const validIpAddressRegex = /^([a-zA-Z0-9]+@){0,1}(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;
const validHostnameRegex = /^([a-zA-Z0-9]+@){0,1}(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/;
// get history of kubectl contexts
function get_kubectxt(socket) {
try {
const cmd = 'kubectl config view -o jsonpath="{.contexts}"';
exec(cmd, (error, stdout, stderr) => {
if (error)
throw (error);
socket.send(JSON.stringify({
cmd: 'kubectxt',
result: stdout
}));
});
} catch (e) {
return { cmd: 'kubectxt', error: e };
}
}
// get history of SSH commands
function get_history(socket) {
try {
const cmd = `cat ~/.bash_history | awk '{if (\$1 == \"ssh\" && \$2 ~ /^[a-z0-9]/) {print \$2}}' | tail -50 | sort -u`;
exec(cmd, (error, stdout, stderr) => {
if (error)
throw (error);
socket.send(JSON.stringify({
cmd: 'history',
result: stdout
.split(/\n/)
.filter(h => h.match(validHostnameRegex) || h.match(validIpAddressRegex))
.filter(s => s.length > 1)
}));
});
} catch (e) {
return { cmd: 'history', error: e };
}
}
// get all hosts currently SSH connected
function get_hosts(socket) {
try {
const cmd = `pgrep -fla "^ssh " || true`;
exec(cmd, (error, stdout, stderr) => {
if (error)
throw (error);
let hosts = stdout.split(/\n/)
.map(s => s.replace(/^[0-9]+ +ssh +/, ''))
.filter(h => h.match(validHostnameRegex) || h.match(validIpAddressRegex))
.filter(s => s.length > 1);
hosts.push('localhost');
socket.send(JSON.stringify({
cmd: 'hosts',
result: hosts
}));
});
} catch (e) {
return { cmd: 'hosts', error: e };
}
}
// Return all probes including initial flag so a frontend knows where to start
function get_probes(socket) {
let output = {};
Object.keys(probes).forEach(function (probe) {
let p = probes[probe];
output[probe] = {
name: p.name,
command: p.command,
initial: p.initial,
refresh: p.refresh,
local: p.local,
localOnly: p.localOnly,
localFilter: p.localFilter
};
});
socket.send(JSON.stringify({
cmd: 'probes',
result: output
}));
}
function runFilter(socket, msg) {
// Use only a single file here as we allow only one filter run at a time below
let tmpfile = '/tmp/wurmterm_localhost_filter';
fs.writeFile(tmpfile, msg.stdout, function (err) {
if (err) {
console.log(err);
msg.stdout = "";
msg.stderr = "Local filter execution failed, writing temporary file failed!";
socket.send(JSON.stringify(msg));
}
});
if (undefined === proxies[':localhost_filter']) {
proxies[':localhost_filter'] = new StatefulProcessCommandProxy({
name: ':localhost_filter',
max: 1,
min: 1,
idleTimeoutMS: 60000,
logFunction: function (severity, origin, msg) {
//console.log(severity.toUpperCase() + " " +origin+" "+ msg);
},
processCommand: "/bin/bash",
processArgs: [],
processRetainMaxCmdHistory: 0,
processInvalidateOnRegex: {
//'stderr':[{regex:'.*error.*',flags:'ig'}]
},
processCwd: './',
processUid: null,
processGid: null,
initCommands: ['LANG=C;echo'], // to catch banners and pseudo-terminal warnings
validateFunction: function (processProxy) {
return processProxy.isValid();
},
});
}
proxies[':localhost_filter'].executeCommands([
`cat ${tmpfile} | ${probes[msg.probe].localFilter}`,
`rm ${tmpfile}`
]).then(function (res) {
msg.stdout = res[0].stdout;
msg.stderr = res[0].stderr;
socket.send(JSON.stringify(msg));
});
}
function getProxy(host) {
if (undefined === proxies[host]) {
proxies[host] = new StatefulProcessCommandProxy({
name: "proxy_" + host,
max: 1,
min: 1,
idleTimeoutMS: 15000,
logFunction: function (severity, origin, msg) {
//console.log(severity.toUpperCase() + " " +origin+" "+ msg);
},
processCommand: 'scripts/generic.sh',
processArgs: [host],
processRetainMaxCmdHistory: 0,
processInvalidateOnRegex: {
'stderr': [{ regex: '.*error.*', flags: 'ig' }]
},
processCwd: './',
processUid: null,
processGid: null,
initCommands: ['LANG=C;echo'], // to catch banners and pseudo-terminal warnings
validateFunction: function (processProxy) {
return processProxy.isValid();
},
});
}
return proxies[host];
}
function probeWS(socket, host, probe) {
try {
if (!(probe in probes)) {
return { host: host, probe: probe, error: 'No such probe' };
}
getProxy(host).executeCommands([probes[probe].command]).then(function (res) {
let msg = {
cmd: 'probe',
host: host,
probe: probe,
stdout: res[0].stdout,
stderr: res[0].stderr,
next: []
};
if ('name' in probes[probe]) msg.name = probes[probe].name;
if ('render' in probes[probe]) msg.render = probes[probe].render;
if ('type' in probes[probe]) msg.type = probes[probe].type;
// Suggest followup probes
for (let p in probes) {
if (probes[p]['if'] === probe && -1 !== res[0].stdout.indexOf(probes[p].matches))
msg.next.push(p);
}
if (undefined !== probes[probe].localFilter) {
runFilter(socket, msg);
} else {
socket.send(JSON.stringify(msg));
}
return;
}).catch(function (e) {
return { cmd: 'probe', host: host, probe: probe, error: e };
});
} catch (e) {
return { cmd: 'probe', host: host, probe: probe, error: e };
}
}
function run(socket, host, id, cmd) {
try {
getProxy(host).executeCommands([cmd]).then(function (res) {
let msg = {
cmd: 'run',
shell: cmd,
host: host,
id: id,
stdout: res[0].stdout,
stderr: res[0].stderr
};
socket.send(JSON.stringify(msg));
return;
}).catch(function (e) {
return { cmd: 'run', host: host, id: id, error: e };
});
} catch (e) {
return { cmd: 'run', host: host, id: id, error: e };
}
}
// Setup CORS '*' to support PWAs
var corsOptions = {
origin: "*",
optionsSuccessStatus: 200,
methods: "GET, PUT"
};
app.use(cors(corsOptions));
const server = http.createServer(app).listen(config.server.port);
const wsServer = new WebSocket.Server({
server: server,
path: "/wurmterm"
});
var clientAuth = [];
var credential = Buffer.from(config.client.auth, 'base64').toString();
wsServer.on('connection', (ws, req, client) => {
clientAuth[ws] = false;
ws.on('error', console.error);
// Send a version so frontend can check for compatibility
ws.send(JSON.stringify({
cmd: 'version',
value: '0.9.1'
}));
ws.on('message', function (message) {
// Auth message handling
let m = ('' + message).match(/^auth (\w+)$/);
if (m && m[1] && (m[1] === credential)) {
clientAuth[ws] = true;
ws.send(JSON.stringify({
cmd: 'auth',
result: 0
}));
return;
}
// Bail out if not authorized
if (!clientAuth[ws]) {
ws.send(JSON.stringify({
cmd: 'auth',
result: 1
}));
return;
}
// General syntax is "<command>[ <parameters>]"
m = ('' + message).match(/^(\w+)( (.+))?$/m);
if (m) {
let cmd = m[1];
let params = m[3];
if (cmd === 'hosts')
return get_hosts(ws);
if (cmd === 'probes')
return get_probes(ws);
if (cmd === 'history')
return get_history(ws);
if (cmd === 'kubectxt')
return get_kubectxt(ws);
if (cmd === 'run') {
// we expect message in format "run <host>:::<id>:::<cmd>"
let tmp = params.split(/:::/);
return run(ws, tmp[0], tmp[1], tmp[2]);
}
if (cmd === 'probe') {
// we expect message in format "probe <host>:::<probe>"
let tmp = params.split(/:::/);
return probeWS(ws, tmp[0], tmp[1]);
}
}
ws.send(JSON.stringify({
cmd: m[1],
error: 'Unsupported command'
}));
});
ws.on('close', function (reasonCode, description) {
});
});
console.log(`Server running at ws://${config.server.host}:${config.server.port}/`);