summaryrefslogtreecommitdiffstats
path: root/scripts/unet-cli
blob: 376162dd1fcd192d3ca7c4d96e758699ffbd123e (plain)
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#!/usr/bin/env ucode
'use strict';

import { access, basename, dirname, mkstemp, open, readfile, writefile, popen } from 'fs';

function assert(cond, message) {
	if (!cond) {
		warn(message, "\n");
		exit(1);
	}

	return true;
}

let unet_tool = "unet-tool";
let script_dir = sourcepath(0, true);

if (basename(script_dir) == "scripts") {
	unet_tool = `${dirname(script_dir)}/unet-tool`;
	assert(access(unet_tool, "x"), "unet-tool missing");
}

let args = {};

const defaults = {
	port: 51830,
	pex_port: 51831,
	keepalive: 10,
};

const usage_message = `Usage: ${basename(sourcepath())} [<flags>] <file> <command> [<args>] [<option>=<value> ...]

     Commands:
      - create:					Create a new network file
      - import <name/path>:			Import signed network config
      - set-config:				Change network config parameters
      - add-host <name>:			Add a host
      - add-local-host <name>:			Add a local OpenWrt host directly
      - add-ssh-host <name> <host>:		Add a remote OpenWrt host via SSH
						(<host> can contain SSH options as well)
      - set-host <name>:			Change host settings
      - set-local-host <name>:			Update local host settings
      - set-ssh-host <name> <host>:		Update local and remote host settings
      - add-service <name>:			Add a service
      - set-service <name>:			Change service settings
      - sign					Sign network data

     Flags:
      -p:					Print modified JSON instead of updating file

     Options:
      - config options (create, set-config):
	port=<val>				set tunnel port (default: ${defaults.port})
	pex_port=<val>				set peer-exchange port (default: ${defaults.pex_port}, 0: disabled)
	keepalive=<val>				set keepalive interval (seconds, 0: off, default: ${defaults.keepalive})
	seed[=<rounds>]				create network private key from seed passphrase
	stun=[+|-]<host:port>[,<host:port>...]	set/add/remove STUN servers
      - host options (add-host, add-local-host, add-ssh-host, set-host):
	key=<val>				set host public key (required for add-host)
	port=<val>				set host tunnel port number
	pex_port=<val>				set host peer-exchange port (default: network pex_port, 0: disabled)
	groups=[+|-]<val>[,<val>...]		set/add/remove groups that the host is a member of
	ipaddr=[+|-]<val>[,<val>...]		set/add/remove host ip addresses
	subnet=[+|-]<val>[,<val>...]		set/add/remove host announced subnets
	endpoint=<val>				set host endpoint address
	gateway=<name>				set host gateway (using name of other host)
     - ssh host options (add-local-host, set-local-host, add-ssh-host, set-ssh-host)
	auth_key=<key>				use <key> as public auth key on the remote host
	priv_key=<key>				use <key> as private host key on the remote host (default: generate a new key)
	interface=<name>			use <name> as interface in /etc/config/network on the remote host
	domain=<name>				use <name> as hosts file domain on the remote host (default: unet)
	connect=<val>[,<val>...]		set IP addresses that the host will contact for network updates
	tunnels=<ifname>:<service>[,...]	set active tunnel devices
	dht=0|1					set DHT enabled
	zone=<name>				set interface zone (default: lan, "-": unset)
     - service options (add-service, set-service):
	type=<val>				set service type (required for add-service)
	members=[+|-]<val>[,<val>...]		set/add/remove service member hosts/groups
     - vxlan service options (add-service, set-service):
	id=<val>				set VXLAN ID
	port=<val>				set VXLAN port
	mtu=<val>				set VXLAN device MTU
	forward_ports=[+|-]<val>[,<val>...]	set members allowed to receive broadcast/multicast/unknown-unicast
     - sign options:
	upload=<ip>[,<ip>...]			upload signed file to hosts

`;

function usage() {
	warn(usage_message);
	return 1;
}

if (length(ARGV) < 2)
	exit(usage());

let file = shift(ARGV);
let command = shift(ARGV);

const field_types = {
	int: function(object, name, val) {
		object[name] = int(val);
	},
	string: function(object, name, val) {
		object[name] = val;
	},
	array: function(object, name, val) {
		let op = substr(val, 0, 1);

		if (op == "+" || op == "-") {
			val = substr(val, 1);
			object[name] ??= [];
		} else {
			op = "=";
			object[name] = [];
		}

		let vals = split(val, ",");
		for (val in vals) {
			object[name] = filter(object[name], function(v) {
				return v != val
			});
			if (op != "-")
				push(object[name], val);
		}

		if (!length(object[name]))
			delete object[name];
	},
};

const service_field_types = {
	vxlan: {
		id: "int",
		port: "int",
		mtu: "int",
		forward_ports: "array",
	},
};

const ssh_script = `

set_list() {
	local field="$1"
	local val="$2"

	first=1
	for cur in $val; do
		if [ -n "$first" ]; then
			cmd=set
		else
			cmd=add_list
		fi
		uci $cmd "network.$INTERFACE.$field=$cur"
		first=
	done
}
set_interface_attrs() {
	[ -n "$AUTH_KEY" ] && uci set "network.$INTERFACE.auth_key=$AUTH_KEY"
	[ -n "$DHT" ] && uci set "network.$INTERFACE.dht=$DHT"
	set_list connect "$CONNECT"
	set_list tunnels "$TUNNELS"
	uci set "network.$INTERFACE.domain=$DOMAIN"
	[ -n "$ZONE" ] && {
		if [ "$ZONE" = "-" ]; then
			uci delete "network.$INTERFACE.zone"
		else
			uci set "network.$INTERFACE.zone=$ZONE"
		fi
	}

}

check_interface() {
	[ "$(uci -q get "network.$INTERFACE")" = "interface" -a "$(uci -q get "network.$INTERFACE.proto")" = "unet" ] && return 0
	uci batch <<EOF
set network.$INTERFACE=interface
set network.$INTERFACE.proto=unet
set network.$INTERFACE.device=$INTERFACE
EOF
}

check_interface_key() {
	key="$(uci -q get "network.$INTERFACE.key" | unet-tool -q -H -K -)"
	[ -n "$key" ] || {
		uci set "network.$INTERFACE.key=$(unet-tool -G)"
		key="$(uci get "network.$INTERFACE.key" | unet-tool -H -K -)"
	}
	echo "key=$key"
}

check_interface
check_interface_key
set_interface_attrs
uci commit
reload_config
ifup $INTERFACE
`;

let print_only = false;

function fetch_args() {
	for (let arg in ARGV) {
		let vals = split(arg, "=", 2);
		args[vals[0]] = vals[1];
	}
}

function set_field(typename, object, name, val) {
	if (!field_types[typename]) {
		warn(`Invalid type ${type}\n`);
		return;
	}

	if (type(val) != "string")
		return;

	if (val == "") {
		delete object[name];
		return;
	}

	field_types[typename](object, name, val);
}

function set_fields(object, list) {
	for (let f in list)
		set_field(list[f], object, f, args[f]);
}

function set_host(host) {
	set_fields(host, {
		key: "string",
		endpoint: "string",
		gateway: "string",
		port: "int",
		ipaddr: "array",
		subnet: "array",
		groups: "array",
	});
	set_field("int", host, "peer-exchange-port", args.pex_port);
}

function set_service(service) {
	set_fields(service, {
		type: "string",
		members: "array",
	});

	if (service_field_types[service.type])
		set_fields(service.config, service_field_types[service.type]);
}

function key_arg(file, net_data) {
	let rounds = net_data.config.rounds;
	let salt = net_data.config.salt;
	if (salt && rounds > 0)
		return `-p -s ${rounds},${salt}`;

	return `-K ${file}.key`;
}

function sync_host(host, net_data, command) {
	let interface = args.interface ?? "unet";
	let connect = replace(args.connect ?? "", ",", " ");
	let auth_key = args.auth_key ?? net_data.config.id;
	let tunnels = replace(replace(args.tunnels ?? "", ",", " "), ":", "=");
	let domain = args.domain ?? "unet";
	let zone = args.zone;
	let dht;

	if (command == "add-host")
		zone ??= "lan";
	else
		zone ??= "";

	if (args.dht == "1" || args.dht == "0")
		dht = args.dht;
	else
		dht = "";

	if (!auth_key) {
		let fh = mkstemp();
		system(`${unet_tool} -q -P -K ${file}.key >&${fh.fileno()}`);
		fh.seek();
		auth_key = fh.read("line");
		fh.close();
		auth_key = replace(auth_key, "\n", "");
		if (auth_key == "") {
			warn("Could not read auth key\n");
			exit(1);
		}
	}

	let fh = mkstemp();
	fh.write(`
INTERFACE='${interface}'
CONNECT='${connect}'
AUTH_KEY='${auth_key}'
TUNNELS='${tunnels}'
DOMAIN='${domain}'
DHT='${dht}'
ZONE='${zone}'
`);
	fh.write(ssh_script);
	fh.flush();
	fh.seek();

	let fh2 = mkstemp();
	let ssh = host ? "ssh " + host : "";
	system(`${ssh} sh <&${fh.fileno()} >&${fh2.fileno()}`);
	fh.close();

	let data = {}, line;

	fh2.seek();
	while (line = fh2.read("line")) {
		let vals = match(line, /^(.[[:alnum:]_-]*)=(.*)\n$/);
		assert(vals, `Invalid argument: ${line}`);
		data[vals[1]] = vals[2]
	}
	fh2.close();

	assert(data.key, "Could not read host key from SSH host");

	args.key = data.key;
}

while (substr(ARGV[0], 0, 1) == "-") {
	let opt = shift(ARGV);
	if (opt == "--")
		break;
	else if (opt == "-p")
		print_only = true;
	else
		exit(usage());
}

let import_file, hostname, ssh_host, servicename;

if (command == "import") {
	import_file = shift(ARGV);
	assert(import_file, "Missing import file argument");
}

if (command in [ "add-host", "set-host", "add-local-host", "set-local-host", "add-ssh-host", "set-ssh-host" ]) {
	hostname = shift(ARGV);
	assert(hostname, "Missing host name argument");
}

if (command in [ "add-ssh-host", "set-ssh-host" ]) {
	ssh_host = shift(ARGV);
	assert(ssh_host, "Missing SSH host/user argument");
}

if (command in [ "add-service", "set-service" ]) {
	servicename = shift(ARGV);
	assert(servicename, "Missing service name argument");
}

fetch_args();

let net_data;

if (command == "import") {
	if (!access(import_file) &&
	    index(import_file, "/") < 0)
		import_file = "/etc/unetd/" + import_file + ".bin";

	assert(access(import_file), "Invalid import file name");
	if (system(`${unet_tool} -b ${import_file} -T -o ${file}`))
		exit(1);
}

if (command == "create") {
	net_data = {
		config: {},
		hosts: {},
		services: {}
	};
} else {
	let fh = open(file);
	assert(fh, `Could not open input file ${file}`);

	try {
		net_data = json(fh);
	} catch(e) {
		assert(false, `Could not parse input file ${file}`);
	}
}

if (command in [ "add-local-host", "set-local-host" ]) {
	command = replace(command, "local-", "");
	sync_host(null, net_data, command);
}

if (command in [ "add-ssh-host", "set-ssh-host" ]) {
	command = replace(command, "ssh-", "");
	sync_host(ssh_host, net_data, command);
}

if (command == "sign") {
	let ret = system(`${unet_tool} -S ${key_arg(file, net_data)} -o ${file}.bin ${file}`);
	if (ret != 0)
		exit(ret);

	let pubkey = trim(popen(`unet-tool -b ${file}.bin -P`).read("all"));
	if (pubkey != net_data.config.id) {
		warn(`Signing key '${pubkey}' does not match network key '${net_data.config.id}'`);
		exit(1);
	}

	if (args.upload) {
		for (let host in split(args.upload, ",")) {
			warn(`Uploading ${file}.bin to ${host}\n`);
			ret = system(`${unet_tool} -U ${host} ${file}.bin`);
			if (ret)
				warn("Upload failed\n");
		}
	}
	exit(0);
}

switch (command) {
case 'import':
	break;
case 'create':
	for (let key, val in defaults)
		args[key] ??= `${val}`;

	// fallthrough
case 'set-config':
	set_fields(net_data.config, {
		port: "int",
		keepalive: "int",
	});
	set_field("int", net_data.config, "peer-exchange-port", args.pex_port);
	set_field("array", net_data.config, "stun-servers", args.stun);

	let seed_arg;

	if ("seed" in args) {
		let salt = readfile("/dev/urandom", 16);
		salt = map(split(salt, ""), (v) => ord(v));
		salt = join("", map(salt, (v) => sprintf("%02x", v)));
		net_data.config.salt = salt;
		net_data.config.rounds = int(args.seed ?? 10000);
		delete net_data.config.id;
		seed_arg = true;
	}

	if (!access(`${file}.key`) && !seed_arg &&
	    system(`${unet_tool} -G -o ${file}.key`)) {
		warn("Failed to generate key\n");
		exit(1);
	}

	if (!net_data.config.id) {
		net_data.config.id = trim(popen(`unet-tool -P -p ${key_arg(file, net_data)}`).read("all"));
		if (!net_data.config.id)
			exit(1);
	}

	break;

case 'add-host':
	net_data.hosts[hostname] = {};
	assert(args.key, "Missing host key");
	set_host(net_data.hosts[hostname]);
	break;

case 'set-host':
	assert(net_data.hosts[hostname], `Host '${hostname}' does not exist`);
	set_host(net_data.hosts[hostname]);
	break;

case 'add-service':
	net_data.services[servicename] = {
		config: {},
		members: [],
	};
	assert(args.type, "Missing service type");
	set_service(net_data.services[servicename]);
	break;

case 'set-service':
	assert(net_data.services[servicename], `Service '${servicename}' does not exist`);
	set_service(net_data.services[servicename]);
	break;

default:
	assert(false, "Unknown command");
}

const net_data_json = sprintf("%.J\n", net_data);

if (print_only)
	print(net_data_json);
else
	writefile(file, net_data_json);