This repository has been archived by the owner on May 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
381 lines (324 loc) · 10.5 KB
/
index.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
'strict'
const { /*execSync,*/ exec } = require('child_process')
const util = require('util')
const fs = require('fs')
const url = require('url')
const yaml = require('js-yaml');
const { createProfile,
syscmd,
waitPhoneHome,
getContainerIp4Address
}
= require('./ffvpn-prof.js')
/////////////////////////////////////////////////////////////
// Parameters:
const timezone = ""
const sshKeyFilename = `/home/${process.env.USER}/.ssh/to-ffvpn`
const vpnClientCertFilename = `/home/${process.env.USER}/ffvpn-client.ovpn`
const lxcImageSrc = `ubuntu:18.04`
const lxcImageAlias = `ub18-im`
const lxcContName = `ub18-ffvpn`
const lxcCopyProfileName = 'default'
const lxcProfileName = 'ffvpn-prof'
const lxcContBridgeName = 'lxdbr0'
const phoneHomePort = 3000
const contUsername = 'ubunutu'
// end of Parameters
//////////////////////////////////////////
// Obviated by using openbox window manager
// const dropDownFixMsg =
// `#### NOTE! ####
// You may find that when clicking on firefox menu icon the menu doesn't appear correctly.
// To fix that try typing 'about:profiles' into the address bar, and then clicking on
// "Restart without addons". When Firefox reopens, the menu *might* work.
// `
// package_upgrade: true, ssha_authorized_keys, timezone
// will be added internally
var cloudInitJSON = {
// "locale": "en_US.UTF-8",
"locale": process.env.LANG,
"packages": [
"firefox",
"openvpn",
"xdotool", // necessary only when XServerXephyr will be 'true' at browse time.
"xserver-xephyr",
"pulseaudio",
"xsel",
"openbox"
],
"runcmd": [
]
}
function getNetworkInfo(){
let networkFromCDN = yaml.safeLoad(syscmd(`lxc network show ${lxcContBridgeName}`)).
config['ipv4.address']
let networkToAddr = networkFromCDN.split('/')[0]
return {
fromCDN:networkFromCDN,
toAddr:networkToAddr
}
}
function makeUfwRule(networkInfo){
let ret =
`sudo ufw allow from ${networkInfo.fromCDN} to ${networkInfo.toAddr} `
+ `port ${phoneHomePort} proto tcp`;
return ret
}
async function initialize(args) {
// create an instance of a container from that image
let doUfwRule = true;
if (args.indexOf('-nufw')>=0)
doUfwRule = false;
let noCopyHostTimezone = false;
if (args.indexOf('-ntz')>=0)
noCopyHostTimezone = false;
// if name exists delete it
let clist = JSON.parse(syscmd(`lxc list --format json`))
if (clist.find(c=>c.name==lxcContName))
syscmd(`lxc delete --force ${lxcContName}`)
// create key
if (!(fs.existsSync(`${sshKeyFilename}.pub`) &&
fs.existsSync(`${sshKeyFilename}`))) {
if (fs.existsSync(`${sshKeyFilename}.pub`))
fs.unlinkSync(`${sshKeyFilename}.pub`)
if (fs.existsSync(`${sshKeyFilename}`))
fs.unlinkSync(`${sshKeyFilename}`)
syscmd(`ssh-keygen -f ${sshKeyFilename} -N ''`)
}
if (!(fs.existsSync(`${sshKeyFilename}.pub`) &&
fs.existsSync(`${sshKeyFilename}`))) {
throw `failed to create ssh key ${sshKeyFilename}`
}
console.log("KEY done ...")
networkInfo = getNetworkInfo();
// the file containing the fix for openvpn-client to run in, and where it should go
let overrideContFn = `/etc/systemd/system/openvpn-client\@.service.d/override.conf`
// create profile
await createProfile(
lxcCopyProfileName,
lxcProfileName,
cloudInitJSON,
`${sshKeyFilename}.pub`,
networkInfo, phoneHomePort,
'[Service]\nLimitNPROC=infinity\n',
overrideContFn,
noCopyHostTimezone
)
console.log("PROFILE done ...")
// copy the lxc image (if already exists does not fail)
if (JSON.parse(syscmd(`lxc image list ${lxcImageAlias} --format json`)).length==0) {
syscmd(`lxc image copy ${lxcImageSrc} local: --alias ${lxcImageAlias}`)
}
console.log("IMAGE done ...")
if (doUfwRule){
//console.log(phoneHomeInfo)
//console.log('DEBUG: ',makeUfwRule(networkInfo))
let ufwRuleCmd = makeUfwRule(networkInfo)
console.log(`ADDING UFW RULE for phome_home:\n${ufwRuleCmd}`)
console.log(syscmd(ufwRuleCmd))
}
// set up receiver for cloud init phone home signalling cloud init end
var promPhoneHome = waitPhoneHome(networkInfo.toAddr, phoneHomePort)
// create the container with cloud init customization
syscmd(`lxc launch ${lxcImageAlias} ${lxcContName} -p ${lxcProfileName}`)
console.log("LAUNCH executed, waiting for phone home to signal cloud init finished ...")
await promPhoneHome;
// wait until cloud init has finished
console.log("CONTAINER has finished cloud init")
var contip4 = getContainerIp4Address(lxcContName)
console.log("CONTAINER ip4 address is " + contip4)
// Copy the vpn client cert to container.
// For privacy's sake we didn't put cert in cloud-init data.
syscmd(`lxc file push ${vpnClientCertFilename} ` +
`${lxcContName}/etc/openvpn/client/client.conf --gid 0 --uid 0`)
console.log(syscmd(`lxc exec ${lxcContName} -- systemctl start openvpn-client@client`))
}
async function browse(args) {
let XServerXephyr=true
if (args.indexOf('-nxephyr')>=0)
XServerXephyr = false;
let xephyrPassThruArgs=''
if (args.indexOf('-xephyrargs')>=0){
xephyrPassThruArgs = args[args.indexOf('-xephyrargs')+1]
}
let SCREENSIZE =
syscmd(`xdpyinfo | grep dimensions`).split(' ').find(w=>w.match(/^[\d]+x[\d]+$/));
if (args.indexOf('-screen')>=0){
SCREENSIZE = args[args.indexOf('-screen')+1]
} else {
console.log(`detected host screensize of ${SCREENSIZE}`)
}
configPulseAudioOnHost();
const setTimeoutPromise = util.promisify(setTimeout);
var contip4 = getContainerIp4Address(lxcContName)
if (XServerXephyr) {
// console.log(dropDownFixMsg)
let rcmd = `
Xephyr -ac -screen ${SCREENSIZE} -resizeable -br -zap ${xephyrPassThruArgs} :2 &
sleep 1
DISPLAY=:2 openbox &
DISPLAY=:2 PULSE_SERVER=tcp:localhost:44713 firefox &
#sleep 3
#DISPLAY=:2 xdotool search --onlyvisible --class Firefox windowsize 100% 100%
`
console.log('starting firefox on Xephyr')
syscmd(`ssh -Y -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no `
+ `-R 44713:localhost:4713 `
+ `-i ${sshKeyFilename} ubuntu@${contip4} /bin/bash "${rcmd}" &`)
console.log('firefox on Xephyr finished')
} else { // XServerXephyr == false
syscmd(`ssh -Y -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no `
+ `-R 44713:localhost:4713 `
+ `-i ${sshKeyFilename} ubuntu@${contip4} `
+ `PULSE_SERVER=tcp:localhost:44713 firefox &`)
console.log('Firefox started (no Xephyr)')
}
}
function configPulseAudioOnHost() {
//set pulseaudio to accept audio from host
let networkInfo = getNetworkInfo()
// audio on host side
// create a new ~/.config/pulse/default.pa file
let defPa = fs.readFileSync(`/etc/pulse/default.pa`)
defPa = defPa +
`load-module module-native-protocol-tcp `
+ `port=4713 auth-ip-acl=127.0.0.1`
+ `\n`
;
fs.mkdirSync(`/home/${process.env.USER}/.config/pulse`, { recursive: true });
fs.writeFileSync( `/home/${process.env.USER}/.config/pulse/default.pa`, defPa)
// kill pulseaudio, it will load the new config and self reboot
syscmd(`pulseaudio --kill`)
}
function notify_send(title, msg){
title = title.replace(/"/g, '\\"');
msg = msg.replace(/"/g, '\\"');
//msg = msg.replace(/'/g, '\\'')
syscmd(`notify-send "${title}" "${msg}"`);
}
async function clipToCont(){
var contip4 = getContainerIp4Address(lxcContName)
var clipValue
try {
clipValue = syscmd('xsel --clipboard --output');
} catch(e) {
throw 'host clipboard empty';
}
let cmd2 = `ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ubuntu@${contip4} 'xsel --clipboard --input --display :2'`;
await new Promise((resolve, reject)=>{
var proc = exec(cmd2, (error, stdout, stderr) => {
if (error) {
reject(error);
}
resolve()
});
if (!proc.stdin.write(clipValue))
reject('pipe write failed')
proc.stdin.end()
})
}
async function clipFromCont(){
var contip4 = getContainerIp4Address(lxcContName)
var clipValue
let cmd1 = `ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ubuntu@${contip4} 'xsel --clipboard --output --display :2'`;
let cmd2 = `xsel --clipboard --input`;
let clipVal = syscmd(cmd1)
await new Promise((resolve, reject)=>{
var proc = exec(cmd2, (error, stdout, stderr) => {
if (error) {
reject(error);
}
resolve()
});
if (true) {
if (!proc.stdin.write(clipVal))
reject('pipe write failed')
proc.stdin.end()
}
})
}
async function clipNotify(to0from1){
let f = to0from1 ? clipFromCont : clipToCont;
let n = to0from1 ? "clipFromCont" : "clipToCont";
let err;
await f()
.then(()=>{
notify_send(n + ": SUCCESS", "")
})
.catch((e)=>{
notify_send(n + ": FAIL", e.toString())
err=e
})
if (err) throw err;
}
function help(){
let usage=`
================
Usage:
- node index.js init [-nufw] [-ntz] [-screen]
Initialize container. When done, browser will appear automatically, with Xephyr.
-nufw:
Don't automatically add ufw rule required for container init-completion phone-home signal.
Use when ufw is not the host firewall, or when sudo requires a password.
-ntz:
Don't use host /etc/timezone in container, the default is UTC.
- node index.js browse [-nxephyr] [-xephyrargs <string of pass thru args>]
Launch Firefox browser
-nxephyr:
Don't use Xephyr on container, use host Xserver directly
-xephyrargs <string of pass thru args>]
Pass string of args directly to invocation of Xephyr
-screen <W>x<H>
Initial size of Xephyr screen. Default is taken from host screen size.
- node index.js ufwRule
Print out what the ufw rule would be to allow container 'phone-home' on init-completion.
- node index.js clip-to-cont
Copy the content of the host clipboard to the container clipboard.
It is expected this call would be mapped to a shortcut key.
- node index.js clip-from-cont
Copy the content of the container clipboard to the host clipboard.
It is expected this call would be mapped to a shortcut key.
`
console.log(usage)
}
async function main(){
// console.log(process.argv.length)
// console.log(process.argv)
if (process.argv.length < 3)
help();
else {
switch (process.argv[2]){
case 'init':
await initialize(process.argv.slice(3))
// continue to browse
case 'browse':
await browse(process.argv.slice(3));
break;
case 'ufwRule':
console.log(makeUfwRule(getNetworkInfo()));
break;
// case 'test':
// configPulseAudioOnHost();
// break;
case 'clip-to-cont':
await clipNotify(0);
break;
case 'clip-from-cont':
await clipNotify(1);
break;
default: help();
}
}
}
main()
.then(()=>{
process.exitCode=0
console.log("SUCCESS")
})
.catch(e => {
process.exitCode=1
console.log("FAIL",e)
})
.finally(()=>{
console.log("EXIT")
})