Merge pull request #5400 from systemcrash/wg_pubkey
[project/luci.git] / protocols / luci-proto-wireguard / htdocs / luci-static / resources / protocol / wireguard.js
1 'use strict';
2 'require ui';
3 'require uci';
4 'require rpc';
5 'require form';
6 'require network';
7
8 var generateKey = rpc.declare({
9 object: 'luci.wireguard',
10 method: 'generateKeyPair',
11 expect: { keys: {} }
12 });
13
14 var getPublicAndPrivateKeyFromPrivate = rpc.declare({
15 object: 'luci.wireguard',
16 method: 'getPublicAndPrivateKeyFromPrivate',
17 params: ['privkey'],
18 expect: { keys: {} }
19 });
20
21 var generateQrCode = rpc.declare({
22 object: 'luci.wireguard',
23 method: 'generateQrCode',
24 params: ['privkey', 'psk', 'allowed_ips'],
25 expect: { qr_code: '' }
26 });
27
28 function validateBase64(section_id, value) {
29 if (value.length == 0)
30 return true;
31
32 if (value.length != 44 || !value.match(/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/))
33 return _('Invalid Base64 key string');
34
35 if (value[43] != "=" )
36 return _('Invalid Base64 key string');
37
38 return true;
39 }
40
41 function findSection(sections, name) {
42 for (var i = 0; i < sections.length; i++) {
43 var section = sections[i];
44 if (section['.name'] == name) return section;
45 }
46
47 return null;
48 }
49
50 function generateDescription(name, texts) {
51 return E('li', { 'style': 'color: inherit;' }, [
52 E('span', name),
53 E('ul', texts.map(function (text) {
54 return E('li', { 'style': 'color: inherit;' }, text);
55 }))
56 ]);
57 }
58
59 return network.registerProtocol('wireguard', {
60 getI18n: function() {
61 return _('WireGuard VPN');
62 },
63
64 getIfname: function() {
65 return this._ubus('l3_device') || this.sid;
66 },
67
68 getOpkgPackage: function() {
69 return 'wireguard-tools';
70 },
71
72 isFloating: function() {
73 return true;
74 },
75
76 isVirtual: function() {
77 return true;
78 },
79
80 getDevices: function() {
81 return null;
82 },
83
84 containsDevice: function(ifname) {
85 return (network.getIfnameOf(ifname) == this.getIfname());
86 },
87
88 renderFormOptions: function(s) {
89 var o, ss;
90
91 // -- general ---------------------------------------------------------------------
92
93 o = s.taboption('general', form.Value, 'private_key', _('Private Key'), _('Required. Base64-encoded private key for this interface.'));
94 o.password = true;
95 o.validate = validateBase64;
96 o.rmempty = false;
97
98 var sections = uci.sections('network');
99 var serverName = this.getIfname();
100 var server = findSection(sections, serverName);
101
102 o = s.taboption('general', form.Value, 'public_key', _('Public Key'), _('Base64-encoded public key of this interface for sharing.'));
103 o.rmempty = false;
104 o.write = function() {/* write nothing */};
105
106 o.load = function(s) {
107 return getPublicAndPrivateKeyFromPrivate(server.private_key).then(
108 function(keypair) {
109 return keypair.pub || '';
110 },
111 function(error){
112 return _('Error getting PublicKey');
113 }, this)
114 };
115
116 o = s.taboption('general', form.Button, 'generate_key', _('Generate Key'));
117 o.inputstyle = 'apply';
118 o.onclick = ui.createHandlerFn(this, function(section_id, ev) {
119 return generateKey().then(function(keypair) {
120 var keyInput = document.getElementById('widget.cbid.network.%s.private_key'.format(section_id)),
121 changeEvent = new Event('change'),
122 pubKeyInput = document.getElementById('widget.cbid.network.%s.public_key'.format(section_id));
123
124 keyInput.value = keypair.priv || '';
125 pubKeyInput.value = keypair.pub || '';
126 keyInput.dispatchEvent(changeEvent);
127 });
128 }, s.section);
129
130 o = s.taboption('general', form.Value, 'listen_port', _('Listen Port'), _('Optional. UDP port used for outgoing and incoming packets.'));
131 o.datatype = 'port';
132 o.placeholder = _('random');
133 o.optional = true;
134
135 o = s.taboption('general', form.DynamicList, 'addresses', _('IP Addresses'), _('Recommended. IP addresses of the WireGuard interface.'));
136 o.datatype = 'ipaddr';
137 o.optional = true;
138
139 o = s.taboption('general', form.Flag, 'nohostroute', _('No Host Routes'), _('Optional. Do not create host routes to peers.'));
140 o.optional = true;
141
142 // -- advanced --------------------------------------------------------------------
143
144 o = s.taboption('advanced', form.Value, 'mtu', _('MTU'), _('Optional. Maximum Transmission Unit of tunnel interface.'));
145 o.datatype = 'range(1280,1420)';
146 o.placeholder = '1420';
147 o.optional = true;
148
149 o = s.taboption('advanced', form.Value, 'fwmark', _('Firewall Mark'), _('Optional. 32-bit mark for outgoing encrypted packets. Enter value in hex, starting with <code>0x</code>.'));
150 o.optional = true;
151 o.validate = function(section_id, value) {
152 if (value.length > 0 && !value.match(/^0x[a-fA-F0-9]{1,8}$/))
153 return _('Invalid hexadecimal value');
154
155 return true;
156 };
157
158
159 // -- peers -----------------------------------------------------------------------
160
161 try {
162 s.tab('peers', _('Peers'), _('Further information about WireGuard interfaces and peers at <a href=\'http://wireguard.com\'>wireguard.com</a>.'));
163 }
164 catch(e) {}
165
166 o = s.taboption('peers', form.SectionValue, '_peers', form.TypedSection, 'wireguard_%s'.format(s.section));
167 o.depends('proto', 'wireguard');
168
169 ss = o.subsection;
170 ss.anonymous = true;
171 ss.addremove = true;
172 ss.addbtntitle = _('Add peer');
173
174 ss.renderSectionPlaceholder = function() {
175 return E([], [
176 E('br'),
177 E('em', _('No peers defined yet'))
178 ]);
179 };
180
181 o = ss.option(form.Flag, 'disabled', _('Peer disabled'), _('Enable / Disable peer. Restart wireguard interface to apply changes.'));
182 o.optional = true;
183
184 o = ss.option(form.Value, 'description', _('Description'), _('Optional. Description of peer.'));
185 o.placeholder = 'My Peer';
186 o.datatype = 'string';
187 o.optional = true;
188
189 o = ss.option(form.Value, 'description', _('QR-Code'));
190 o.render = L.bind(function (view, section_id) {
191 var sections = uci.sections('network');
192 var client = findSection(sections, section_id);
193 var serverName = this.getIfname();
194 var server = findSection(sections, serverName);
195
196 var interfaceTexts = [
197 'PrivateKey: ' + _('A random, on the fly generated "PrivateKey", the key will not be saved on the router')
198 ];
199
200 var peerTexts = [
201 'PublicKey: ' + _('The "PublicKey" of that wg interface'),
202 'AllowedIPs: ' + _('The list of this client\'s "AllowedIPs" or "0.0.0.0/0, ::/0" if not configured'),
203 'PresharedKey: ' + _('If available, the client\'s "PresharedKey"')
204 ];
205
206 var description = [
207 E('span', [
208 _('If there are any unsaved changes for this client, please save the configuration before generating a QR-Code'),
209 E('br'),
210 _('The QR-Code works per wg interface, it will be refreshed with every button click and transfers the following information:')
211 ]),
212 E('ul', [
213 generateDescription('[Interface]', interfaceTexts),
214 generateDescription('[Peer]', peerTexts)
215 ])
216 ];
217
218 return E('div', { 'class': 'cbi-value' }, [
219 E('label', { 'class': 'cbi-value-title' }, _('QR-Code')),
220 E('div', {
221 'class': 'cbi-value-field',
222 'style': 'display: flex; flex-direction: column; align-items: baseline;',
223 'id': 'qr-' + section_id
224 }, [
225 E('button', {
226 'class': 'btn cbi-button cbi-button-apply',
227 'click': ui.createHandlerFn(this, function (server, client, section_id) {
228 var qrDiv = document.getElementById('qr-' + section_id);
229 var qrEl = qrDiv.querySelector('value');
230 var qrBtn = qrDiv.querySelector('button');
231 var qrencodeErr = '<b>%q</b>'.format(
232 _('For QR-Code support please install the qrencode package!'));
233
234 if (qrEl.innerHTML != '' && qrEl.innerHTML != qrencodeErr) {
235 qrEl.innerHTML = '';
236 qrBtn.innerHTML = _('Generate New QR-Code')
237 } else {
238 qrEl.innerHTML = _('Loading QR-Code...');
239
240 generateQrCode(server.private_key, client.preshared_key,
241 client.allowed_ips).then(function (qrCode) {
242 if (qrCode == '') {
243 qrEl.innerHTML = qrencodeErr;
244 } else {
245 qrEl.innerHTML = qrCode;
246 qrBtn.innerHTML = _('Hide QR-Code');
247 }
248 });
249 }
250 }, server, client, section_id)
251 }, _('Generate new QR-Code')),
252 E('value', {
253 'class': 'cbi-section',
254 'style': 'margin: 0;'
255 }),
256 E('div', { 'class': 'cbi-value-description' }, description)
257 ])
258 ]);
259 }, this);
260
261 o = ss.option(form.Value, 'public_key', _('Public Key'), _('Required. Base64-encoded public key of peer.'));
262 o.validate = validateBase64;
263 o.rmempty = false;
264
265 o = ss.option(form.Value, 'preshared_key', _('Preshared Key'), _('Optional. Base64-encoded preshared key. Adds in an additional layer of symmetric-key cryptography for post-quantum resistance.'));
266 o.password = true;
267 o.validate = validateBase64;
268 o.optional = true;
269
270 o = ss.option(form.DynamicList, 'allowed_ips', _('Allowed IPs'), _("Optional. IP addresses and prefixes that this peer is allowed to use inside the tunnel. Usually the peer's tunnel IP addresses and the networks the peer routes through the tunnel."));
271 o.datatype = 'ipaddr';
272 o.optional = true;
273
274 o = ss.option(form.Flag, 'route_allowed_ips', _('Route Allowed IPs'), _('Optional. Create routes for Allowed IPs for this peer.'));
275
276 o = ss.option(form.Value, 'endpoint_host', _('Endpoint Host'), _('Optional. Host of peer. Names are resolved prior to bringing up the interface.'));
277 o.placeholder = 'vpn.example.com';
278 o.datatype = 'host';
279
280 o = ss.option(form.Value, 'endpoint_port', _('Endpoint Port'), _('Optional. Port of peer.'));
281 o.placeholder = '51820';
282 o.datatype = 'port';
283
284 o = ss.option(form.Value, 'persistent_keepalive', _('Persistent Keep Alive'), _('Optional. Seconds between keep alive messages. Default is 0 (disabled). Recommended value if this device is behind a NAT is 25.'));
285 o.datatype = 'range(0,65535)';
286 o.placeholder = '0';
287 },
288
289 deleteConfiguration: function() {
290 uci.sections('network', 'wireguard_%s'.format(this.sid), function(s) {
291 uci.remove('network', s['.name']);
292 });
293 }
294 });