summaryrefslogtreecommitdiffhomepage
path: root/protocols/luci-proto-wireguard/root/usr/share/rpcd/ucode/luci.wireguard
blob: fc99919127b25ac17c3f0c21220b7b1bac046fbc (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
// Copyright 2022 Jo-Philipp Wich <jo@mein.io>
// Licensed to the public under the Apache License 2.0.

'use strict';

import { cursor } from 'uci';
import { popen } from 'fs';


function shellquote(s) {
	return `'${replace(s ?? '', "'", "'\\''")}'`;
}

function command(cmd) {
	return trim(popen(cmd)?.read?.('all'));
}


const methods = {
	generatePsk: {
		call: function() {
			return { psk: command('wg genpsk 2>/dev/null') };
		}
	},

	generateKeyPair: {
		call: function() {
			const priv = command('wg genkey 2>/dev/null');
			const pub = command(`echo ${shellquote(priv)} | wg pubkey 2>/dev/null`);

			return { keys: { priv, pub } };
		}
	},

	getPublicAndPrivateKeyFromPrivate: {
		args: { privkey: "privkey" },
		call: function(req) {
			const priv = req.args?.privkey;
			const pub = command(`echo ${shellquote(priv)} | wg pubkey 2>/dev/null`);

			return { keys: { priv, pub } };
		}
	},

	getWgInstances: {
		call: function() {
			const data = {};
			let last_device;
			let qr_pubkey = {};

			const uci = cursor();
			const wg_dump = popen("wg show all dump 2>/dev/null");

			if (wg_dump) {
				for (let line = wg_dump.read('line'); length(line); line = wg_dump.read('line')) {
					const record = split(rtrim(line, '\n'), '\t');

					if (last_device != record[0]) {
						last_device = record[0];
						data[last_device] = {
							name: last_device,
							public_key: record[2],
							listen_port: record[3],
							fwmark: record[4],
							peers: []
						};

						if (!length(record[2]) || record[2] == '(none)')
							qr_pubkey[last_device] = '';
						else
							qr_pubkey[last_device] = `PublicKey = ${record[2]}`;
					}
					else {
						let peer_name;

						uci.foreach('network', `wireguard_${last_device}`, (s) => {
							if (s.public_key == record[1])
								peer_name = s.description;
						});

						const peer = {
							name: peer_name,
							public_key: record[1],
							endpoint: record[3],
							allowed_ips: [],
							latest_handshake: record[5],
							transfer_rx: record[6],
							transfer_tx: record[7],
							persistent_keepalive: record[8]
						};

						if (record[3] != '(none)' && length(record[4]))
							push(peer.allowed_ips, ...split(record[4], ','));

						push(data[last_device].peers, peer);
					}
				}
			}

			return data;
		}
	}
};

return { 'luci.wireguard': methods };