'use strict';
'require fs';
'require ui';
'require dom';
'require uci';
'require rpc';
'require form';
'require network';
'require validation';
'require uqr';
const generateKey = rpc.declare({
object: 'luci.amneziawg',
method: 'generateKeyPair',
expect: { keys: {} }
});
const getPublicAndPrivateKeyFromPrivate = rpc.declare({
object: 'luci.amneziawg',
method: 'getPublicAndPrivateKeyFromPrivate',
params: ['privkey'],
expect: { keys: {} }
});
const generatePsk = rpc.declare({
object: 'luci.amneziawg',
method: 'generatePsk',
expect: { psk: '' }
});
const qrIcon = '';
function validateBase64(section_id, value) {
if (value.length == 0)
return true;
if (value.length != 44 || !value.match(/^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/))
return _('Invalid Base64 key string');
if (value[43] != "=" )
return _('Invalid Base64 key string');
return true;
}
function rangeValidator(max) {
return function(section_id, value) {
if (value.length == 0)
return true;
const m = value.match(/^(\d+)(?:-(\d+))?$/);
if (!m || +m[1] > max || (m[2] != null && (+m[2] > max || +m[2] < +m[1])))
return _('Expecting a value or a range (e.g. 10-20) between 0 and %d').format(max);
return true;
};
}
const validateU16Range = rangeValidator(65535);
const validateU32Range = rangeValidator(4294967295);
function parseRange(value) {
const m = value.match(/^(\d+)(?:-(\d+))?$/);
return m ? [ +m[1], +(m[2] != null ? m[2] : m[1]) ] : null;
}
function validateHeaderRanges(values) {
const ranges = values.map(function(value, index) {
return parseRange(value || String(index + 1));
});
for (let i = 0; i < ranges.length; i++) {
if (!ranges[i])
continue;
for (let j = i + 1; j < ranges.length; j++) {
if (ranges[j] && ranges[i][0] <= ranges[j][1] && ranges[j][0] <= ranges[i][1])
return _('H1-H4 ranges must not overlap');
}
}
return true;
}
function headerRangeValidator(index) {
return function(section_id, value) {
const result = validateU32Range(section_id, value);
if (result !== true)
return result;
const values = [ 'awg_h1', 'awg_h2', 'awg_h3', 'awg_h4' ].map(function(option) {
return this.section.formvalue(section_id, option) || '';
}, this);
values[index] = value;
return validateHeaderRanges(values);
};
}
function validateHeaderProtectionPaddings(values) {
for (let i = 0; i < values.length; i++) {
if (!/^[0-9]+$/.test(values[i] || '') || +values[i] < 12 || +values[i] > 65535)
return _('Header Protection requires S1-S4 to be between 12 and 65535');
}
return true;
}
function validateHeaderProtectionKey(section_id, value) {
const result = validateBase64(section_id, value);
if (result !== true || value.length == 0)
return result;
const values = [ 'awg_s1', 'awg_s2', 'awg_s3', 'awg_s4' ].map(function(option) {
return this.section.formvalue(section_id, option) || '';
}, this);
return validateHeaderProtectionPaddings(values);
}
function parseFlag(value) {
if (/^on$/i.test(value || ''))
return '1';
if (/^off$/i.test(value || ''))
return '0';
if (/^\d+$/.test(value || ''))
return /[1-9]/.test(value) ? '1' : '0';
return null;
}
const stubValidator = {
factory: validation,
apply: function(type, value, args) {
if (value != null)
this.value = value;
return validation.types[type].apply(this, args);
},
assert: function(condition) {
return !!condition;
}
};
function generateDescription(name, texts) {
return E('li', { 'style': 'color: inherit;' }, [
E('span', name),
E('ul', texts.map(function (text) {
return E('li', { 'style': 'color: inherit;' }, text);
}))
]);
}
function buildSVGQRCode(data, code) {
// pixel size 3 for mobile browser
const options = {
pixelSize: 3,
whiteColor: 'white',
blackColor: 'black'
};
try {
const svg = uqr.renderSVG(data, options);
code.style.opacity = '';
dom.content(code, Object.assign(E(svg), {
style: 'width:100%;height:auto'
}));
}
catch (e) {
console.warn('QR generation failed:', e);
code.style.opacity = '';
dom.content(code, E('div', {
'class': 'alert-message warning',
'style': 'margin:0;text-align:center'
}, [
_('QR code generation failed. The configuration may be too large.')
]));
}
}
const cbiKeyPairGenerate = form.DummyValue.extend({
cfgvalue: function(section_id, value) {
return E('button', {
'class': 'btn',
'click': ui.createHandlerFn(this, function(section_id, ev) {
const prv = this.section.getUIElement(section_id, 'private_key'),
pub = this.section.getUIElement(section_id, 'public_key'),
map = this.map;
return generateKey().then(function(keypair) {
prv.setValue(keypair.priv);
pub.setValue(keypair.pub);
map.save(null, true);
});
}, section_id)
}, [ _('Generate new key pair') ]);
}
});
function handleWindowDragDropIgnore(ev) {
ev.preventDefault()
}
return network.registerProtocol('amneziawg', {
getI18n: function() {
return _('AmneziaWG VPN');
},
getIfname: function() {
return this._ubus('l3_device') || this.sid;
},
getPackageName: function() {
return 'amneziawg-tools';
},
isFloating: function() {
return true;
},
isVirtual: function() {
return true;
},
getDevices: function() {
return null;
},
containsDevice: function(ifname) {
return (network.getIfnameOf(ifname) == this.getIfname());
},
renderFormOptions: function(s) {
let o;
// -- general ---------------------------------------------------------------------
o = s.taboption('general', form.Value, 'private_key', _('Private Key'), _('Required. Base64-encoded private key for this interface.'));
o.password = true;
o.validate = validateBase64;
o.rmempty = false;
o = s.taboption('general', form.Value, 'public_key', _('Public Key'), _('Base64-encoded public key of this interface for sharing.'));
o.rmempty = false;
o.write = function() {/* write nothing */};
o.load = function(section_id) {
const privKey = s.formvalue(section_id, 'private_key') || uci.get('network', section_id, 'private_key');
return getPublicAndPrivateKeyFromPrivate(privKey).then(
function(keypair) {
return keypair.pub || '';
},
function(error) {
return _('Error getting PublicKey');
}, this)
};
s.taboption('general', cbiKeyPairGenerate, '_gen_server_keypair', ' ');
o = s.taboption('general', form.Value, 'listen_port', _('Listen Port'), _('Optional. UDP port used for outgoing and incoming packets.'));
o.datatype = 'port';
o.placeholder = _('random');
o.optional = true;
o = s.taboption('general', form.DynamicList, 'addresses', _('IP Addresses'), _('Recommended. IP addresses of the AmneziaWG interface.'));
o.datatype = 'ipaddr';
o.optional = true;
o = s.taboption('general', form.Flag, 'nohostroute', _('No Host Routes'), _('Optional. Do not create host routes to peers.'));
o.optional = true;
o = s.taboption('general', form.Button, '_import', _('Import configuration'), _('Imports settings from an existing AmneziaWG configuration file'));
o.inputtitle = _('Load configuration…');
o.onclick = function() {
return ss.handleConfigImport('full');
};
// -- advanced --------------------------------------------------------------------
o = s.taboption('advanced', form.Value, 'mtu', _('MTU'), _('Optional. Maximum Transmission Unit of tunnel interface.'));
o.datatype = 'range(0,8940)';
o.placeholder = '1420';
o.optional = true;
o = s.taboption('advanced', form.Value, 'fwmark', _('Firewall Mark'), _('Optional. 32-bit mark for packets during firewall processing. Enter value in hex, starting with 0x.'));
o.optional = true;
o.validate = function(section_id, value) {
if (value.length > 0 && !value.match(/^0x[a-fA-F0-9]{1,8}$/))
return _('Invalid hexadecimal value');
return true;
};
// AmneziaWG
try {
s.tab('amneziawg', _('AmneziaWG Settings'), _('Further information about AmneziaWG interfaces and peers at amnezia.org.'));
}
catch(e) {}
o = s.taboption('amneziawg', form.Value, 'awg_jc', _('Jc'), _('Junk packet count.'));
o.datatype = 'uinteger';
o.placeholder = '0';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_jmin', _('Jmin'), _('Junk packet minimum size.'));
o.datatype = 'uinteger';
o.placeholder = '0';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_jmax', _('Jmax'), _('Junk packet maximum size.'));
o.datatype = 'uinteger';
o.placeholder = '0';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_s1', _('S1'), _('Handshake initiation packet junk header size.'));
o.datatype = 'uinteger';
o.placeholder = '0';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_s2', _('S2'), _('Handshake response packet junk header size.'));
o.datatype = 'uinteger';
o.placeholder = '0';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_s3', _('S3'), _('Cookie reply packet junk header size.'));
o.datatype = 'uinteger';
o.placeholder = '0';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_s4', _('S4'), _('Transport packet junk header size.'));
o.datatype = 'uinteger';
o.placeholder = '0';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_h1', _('H1'), _('Handshake initiation packet type header. A range such as 10-20 is also accepted. H1-H4 ranges must not overlap.'));
o.validate = headerRangeValidator(0);
o.placeholder = '1';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_h2', _('H2'), _('Handshake response packet type header. A range such as 10-20 is also accepted.'));
o.validate = headerRangeValidator(1);
o.placeholder = '2';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_h3', _('H3'), _('Handshake cookie packet type header. A range such as 10-20 is also accepted.'));
o.validate = headerRangeValidator(2);
o.placeholder = '3';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_h4', _('H4'), _('Transport packet type header. A range such as 10-20 is also accepted.'));
o.validate = headerRangeValidator(3);
o.placeholder = '4';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_i1', _('I1'), _('First special junk packet signature.'));
o.datatype = 'string';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_i2', _('I2'), _('Second special junk packet signature.'));
o.datatype = 'string';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_i3', _('I3'), _('Third special junk packet signature.'));
o.datatype = 'string';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_i4', _('I4'), _('Fourth special junk packet signature.'));
o.datatype = 'string';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_i5', _('I5'), _('Fifth special junk packet signature.'));
o.datatype = 'string';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_header_protection_key', _('Header Protection Key'), _('Optional. 32-byte key encoded in Base64, used to encrypt and obfuscate packet headers. Must match on both sides and requires S1-S4 to be at least 12.'));
o.validate = validateHeaderProtectionKey;
o.password = true;
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_content_padding_addition', _('Content Padding Addition'), _('Extra bytes appended to transport packets. A range such as 10-20 is also accepted.'));
o.validate = validateU16Range;
o.placeholder = '0';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_rekey_after_time', _('Rekey After Time'), _('Seconds before a session is renegotiated. A range such as 110-130 is also accepted.'));
o.validate = validateU16Range;
o.placeholder = '120';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_rekey_timeout', _('Rekey Timeout'), _('Seconds between handshake retries. A range such as 5-7 is also accepted.'));
o.validate = validateU16Range;
o.placeholder = '5';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_reject_after_time', _('Reject After Time'), _('Seconds after which incoming data for the current session is rejected and a new handshake is initiated. A range such as 170-190 is also accepted.'));
o.validate = validateU16Range;
o.placeholder = '180';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_keepalive_timeout', _('Keepalive Timeout'), _('Seconds to wait after receiving authenticated data when no authenticated packet is sent before sending a keepalive. A range such as 8-12 is also accepted.'));
o.validate = validateU16Range;
o.placeholder = '10';
o.optional = true;
o = s.taboption('amneziawg', form.Value, 'awg_max_handshake_attempts', _('Max Handshake Attempts'), _('Maximum number of handshake retries after timeouts. A range such as 15-20 is also accepted.'));
o.validate = validateU16Range;
o.placeholder = '18';
o.optional = true;
o = s.taboption('amneziawg', form.Flag, 'awg_random_trailers', _('Random Trailers'), _('Append random-length trailers to handshake and transport packets: random bytes for handshakes and zero bytes for transport. Must be enabled on both sides. Content Padding Addition takes priority for transport packets.'));
o.optional = true;
o = s.taboption('amneziawg', form.Flag, 'awg_disable_cookies', _('Disable Cookies'), _('Do not send Handshake Cookie Reply messages. Received cookies are still processed.'));
o.optional = true;
// -- peers -----------------------------------------------------------------------
try {
s.tab('peers', _('Peers'), _('Further information about AmneziaWG interfaces and peers at amnezia.org.'));
}
catch(e) {}
o = s.taboption('peers', form.SectionValue, '_peers', form.GridSection, 'amneziawg_%s'.format(s.section));
o.depends('proto', 'amneziawg');
const ss = o.subsection;
ss.anonymous = true;
ss.addremove = true;
ss.addbtntitle = _('Add peer');
ss.nodescriptions = true;
ss.modaltitle = _('Edit peer');
ss.sortable = true;
ss.handleDragConfig = function(ev) {
ev.stopPropagation();
ev.preventDefault();
ev.dataTransfer.dropEffect = 'copy';
};
ss.handleConfigFile = function(mode, nodes, file, ev) {
const input = nodes.querySelector('textarea'),
reader = new FileReader();
if (file) {
reader.onload = function(rev) {
input.value = rev.target.result.trim();
ss.handleApplyConfig(mode, nodes, file.name, ev);
};
reader.readAsText(file);
}
};
ss.handleDropConfig = function(mode, ev) {
ss.handleConfigFile(mode, ev.currentTarget, ev.dataTransfer.files[0], ev);
ev.stopPropagation();
ev.preventDefault();
};
ss.parseConfig = function(data) {
const lines = String(data).split(/(\r?\n)+/),
config = { peers: [] };
let section = null,
s;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].replace(/#.*$/, '').trim();
if (line.match(/^\[(\w+)\]$/)) {
section = RegExp.$1.toLowerCase();
if (section == 'peer')
config.peers.push(s = {});
else
s = config;
}
else if (section && line.match(/^(\w+)\s*=\s*(.+)$/)) {
const key = RegExp.$1,
val = RegExp.$2.trim();
if (val.length)
s[section + '_' + key.toLowerCase()] = val;
}
}
if (config.interface_address) {
config.interface_address = config.interface_address.split(/[, ]+/);
for (let i = 0; i < config.interface_address.length; i++)
if (!stubValidator.apply('ipaddr', config.interface_address[i]))
return _('Address setting is invalid');
}
if (config.interface_dns) {
config.interface_dns = config.interface_dns.split(/[, ]+/);
for (let i = 0; i < config.interface_dns.length; i++)
if (!stubValidator.apply('ipaddr', config.interface_dns[i], ['nomask']))
return _('DNS setting is invalid');
}
if (!config.interface_privatekey || validateBase64(null, config.interface_privatekey) !== true)
return _('PrivateKey setting is missing or invalid');
if (!stubValidator.apply('port', config.interface_listenport || '0'))
return _('ListenPort setting is invalid');
if (config.interface_headerprotectionkey && validateBase64(null, config.interface_headerprotectionkey) !== true)
return _('HeaderProtectionKey setting is invalid');
const headerValues = [
config.interface_h1 || '1',
config.interface_h2 || '2',
config.interface_h3 || '3',
config.interface_h4 || '4'
];
for (let i = 0; i < headerValues.length; i++)
if (validateU32Range(null, headerValues[i]) !== true)
return _('H1-H4 setting is invalid');
if (validateHeaderRanges(headerValues) !== true)
return _('H1-H4 ranges must not overlap');
if (config.interface_headerprotectionkey && validateHeaderProtectionPaddings([
config.interface_s1,
config.interface_s2,
config.interface_s3,
config.interface_s4
]) !== true)
return _('Header Protection requires S1-S4 to be between 12 and 65535');
const flags = [
[ 'interface_randomtrailers', 'RandomTrailers' ],
[ 'interface_disablecookies', 'DisableCookies' ]
];
for (let i = 0; i < flags.length; i++) {
const key = flags[i][0];
if (config[key] != null) {
config[key] = parseFlag(config[key]);
if (config[key] == null)
return _('%s setting is invalid').format(flags[i][1]);
}
}
for (let i = 0; i < config.peers.length; i++) {
const pconf = config.peers[i];
if (pconf.peer_publickey != null && validateBase64(null, pconf.peer_publickey) !== true)
return _('PublicKey setting is invalid');
if (pconf.peer_presharedkey != null && validateBase64(null, pconf.peer_presharedkey) !== true)
return _('PresharedKey setting is invalid');
if (pconf.peer_allowedips) {
pconf.peer_allowedips = pconf.peer_allowedips.split(/[, ]+/);
for (let j = 0; j < pconf.peer_allowedips.length; j++)
if (!stubValidator.apply('ipaddr', pconf.peer_allowedips[j]))
return _('AllowedIPs setting is invalid');
}
else {
pconf.peer_allowedips = [ '0.0.0.0/0', '::/0' ];
}
if (pconf.peer_endpoint) {
const host_port = pconf.peer_endpoint.match(/^\[([a-fA-F0-9:]+)\]:(\d+)$/) || pconf.peer_endpoint.match(/^(.+):(\d+)$/);
if (!host_port || !stubValidator.apply('host', host_port[1]) || !stubValidator.apply('port', host_port[2]))
return _('Endpoint setting is invalid');
pconf.peer_endpoint = [ host_port[1], host_port[2] ];
}
if (pconf.peer_persistentkeepalive == 'off' || pconf.peer_persistentkeepalive == '0')
delete pconf.peer_persistentkeepalive;
if (validateU16Range(null, pconf.peer_persistentkeepalive || '0') !== true)
return _('PersistentKeepAlive setting is invalid');
}
return config;
};
ss.handleApplyConfig = function(mode, nodes, comment, ev) {
const input = nodes.querySelector('textarea').value,
error = nodes.querySelector('.alert-message'),
cancel = nodes.nextElementSibling.querySelector('.btn'),
config = this.parseConfig(input);
if (typeof(config) == 'string') {
error.firstChild.data = _('Cannot parse configuration: %s').format(config);
error.style.display = 'block';
return;
}
if (mode == 'full') {
const prv = s.formvalue(s.section, 'private_key');
if (prv && prv != config.interface_privatekey && !confirm(_('Overwrite the current settings with the imported configuration?')))
return;
return getPublicAndPrivateKeyFromPrivate(config.interface_privatekey).then(function(keypair) {
s.getOption('private_key').getUIElement(s.section).setValue(keypair.priv);
s.getOption('public_key').getUIElement(s.section).setValue(keypair.pub);
s.getOption('listen_port').getUIElement(s.section).setValue(config.interface_listenport || '');
s.getOption('addresses').getUIElement(s.section).setValue(config.interface_address);
s.getOption('awg_jc').getUIElement(s.section).setValue(config.interface_jc || '');
s.getOption('awg_jmin').getUIElement(s.section).setValue(config.interface_jmin || '');
s.getOption('awg_jmax').getUIElement(s.section).setValue(config.interface_jmax || '');
s.getOption('awg_s1').getUIElement(s.section).setValue(config.interface_s1 || '');
s.getOption('awg_s2').getUIElement(s.section).setValue(config.interface_s2 || '');
s.getOption('awg_s3').getUIElement(s.section).setValue(config.interface_s3 || '');
s.getOption('awg_s4').getUIElement(s.section).setValue(config.interface_s4 || '');
s.getOption('awg_h1').getUIElement(s.section).setValue(config.interface_h1 || '');
s.getOption('awg_h2').getUIElement(s.section).setValue(config.interface_h2 || '');
s.getOption('awg_h3').getUIElement(s.section).setValue(config.interface_h3 || '');
s.getOption('awg_h4').getUIElement(s.section).setValue(config.interface_h4 || '');
s.getOption('awg_i1').getUIElement(s.section).setValue(config.interface_i1 || '');
s.getOption('awg_i2').getUIElement(s.section).setValue(config.interface_i2 || '');
s.getOption('awg_i3').getUIElement(s.section).setValue(config.interface_i3 || '');
s.getOption('awg_i4').getUIElement(s.section).setValue(config.interface_i4 || '');
s.getOption('awg_i5').getUIElement(s.section).setValue(config.interface_i5 || '');
s.getOption('awg_header_protection_key').getUIElement(s.section).setValue(config.interface_headerprotectionkey || '');
s.getOption('awg_content_padding_addition').getUIElement(s.section).setValue(config.interface_contentpaddingaddition || '');
s.getOption('awg_rekey_after_time').getUIElement(s.section).setValue(config.interface_rekeyaftertime || '');
s.getOption('awg_rekey_timeout').getUIElement(s.section).setValue(config.interface_rekeytimeout || '');
s.getOption('awg_reject_after_time').getUIElement(s.section).setValue(config.interface_rejectaftertime || '');
s.getOption('awg_keepalive_timeout').getUIElement(s.section).setValue(config.interface_keepalivetimeout || '');
s.getOption('awg_max_handshake_attempts').getUIElement(s.section).setValue(config.interface_maxhandshakeattempts || '');
s.getOption('awg_random_trailers').getUIElement(s.section).setValue(config.interface_randomtrailers || '0');
s.getOption('awg_disable_cookies').getUIElement(s.section).setValue(config.interface_disablecookies || '0');
if (config.interface_dns)
s.getOption('dns').getUIElement(s.section).setValue(config.interface_dns);
for (let i = 0; i < config.peers.length; i++) {
const pconf = config.peers[i];
const sid = uci.add('network', 'amneziawg_' + s.section);
uci.sections('network', 'amneziawg_' + s.section, function(peer) {
if (peer.public_key == pconf.peer_publickey)
uci.remove('network', peer['.name']);
});
uci.set('network', sid, 'description', comment || _('Imported peer configuration'));
uci.set('network', sid, 'public_key', pconf.peer_publickey);
uci.set('network', sid, 'preshared_key', pconf.peer_presharedkey);
uci.set('network', sid, 'allowed_ips', pconf.peer_allowedips);
uci.set('network', sid, 'persistent_keepalive', pconf.peer_persistentkeepalive);
if (pconf.peer_endpoint) {
uci.set('network', sid, 'endpoint_host', pconf.peer_endpoint[0]);
uci.set('network', sid, 'endpoint_port', pconf.peer_endpoint[1]);
}
}
return s.map.save(null, true);
}).then(function() {
cancel.click();
});
}
else {
return getPublicAndPrivateKeyFromPrivate(config.interface_privatekey).then(function(keypair) {
const sid = uci.add('network', 'amneziawg_' + s.section);
const pub = s.formvalue(s.section, 'public_key');
uci.sections('network', 'amneziawg_' + s.section, function(peer) {
if (peer.public_key == keypair.pub)
uci.remove('network', peer['.name']);
});
uci.set('network', sid, 'description', comment || _('Imported peer configuration'));
uci.set('network', sid, 'public_key', keypair.pub);
uci.set('network', sid, 'private_key', keypair.priv);
for (let i = 0; i < config.peers.length; i++) {
const pconf = config.peers[i];
if (pconf.peer_publickey == pub) {
uci.set('network', sid, 'preshared_key', pconf.peer_presharedkey);
uci.set('network', sid, 'allowed_ips', pconf.peer_allowedips);
uci.set('network', sid, 'persistent_keepalive', pconf.peer_persistentkeepalive);
break;
}
}
return s.map.save(null, true);
}).then(function() {
cancel.click();
});
}
};
ss.handleConfigImport = function(mode) {
const mapNode = ss.getActiveModalMap(),
headNode = mapNode.parentNode.querySelector('h4'),
parent = this.map,
fileInput = E('input', {
'type': 'file',
'accept': '.conf,text/plain,application/octet-stream',
'style': 'display:none'
}),
fileButton = E('button', {
'class': 'btn',
'type': 'button',
'click': function(ev) {
ev.preventDefault();
fileInput.value = '';
fileInput.click();
}
}, [ _('Select file…') ]);
const nodes = E('div', {
'dragover': this.handleDragConfig,
'drop': this.handleDropConfig.bind(this, mode)
}, [
E([], (mode == 'full') ? [
E('p', _('Select, drag or paste a valid *.conf file below to configure the local AmneziaWG interface.'))
] : [
E('p', _('Select, paste or drag a AmneziaWG configuration (commonly wg0.conf) from another system below to create a matching peer entry allowing that system to connect to the local AmneziaWG interface.')),
E('p', _('To configure fully the local AmneziaWG interface from an existing (e.g. provider supplied) configuration file, use the configuration import instead.'))
]),
E('p', [ fileButton, fileInput ]),
E('p', [
E('textarea', {
'placeholder': (mode == 'full')
? _('Paste or drag supplied AmneziaWG configuration file…')
: _('Paste or drag AmneziaWG peer configuration (wg0.conf) file…'),
'style': 'height:5em;width:100%; white-space:pre'
})
]),
E('div', {
'class': 'alert-message',
'style': 'display:none'
}, [''])
]);
fileInput.addEventListener('change', function(ev) {
ss.handleConfigFile(mode, nodes, ev.currentTarget.files[0], ev);
});
const cancelFn = function() {
nodes.parentNode.removeChild(nodes.nextSibling);
nodes.parentNode.removeChild(nodes);
mapNode.classList.remove('hidden');
mapNode.nextSibling.classList.remove('hidden');
headNode.removeChild(headNode.lastChild);
window.removeEventListener('dragover', handleWindowDragDropIgnore);
window.removeEventListener('drop', handleWindowDragDropIgnore);
};
const a = nodes.querySelector('a.full-import');
if (a) {
a.addEventListener('click', ui.createHandlerFn(this, function(mode) {
cancelFn();
this.handleConfigImport('full');
}));
}
mapNode.classList.add('hidden');
mapNode.nextElementSibling.classList.add('hidden');
headNode.appendChild(E('span', [ ' » ', (mode == 'full') ? _('Import configuration') : _('Import as peer') ]));
mapNode.parentNode.appendChild(E([], [
nodes,
E('div', {
'class': 'right'
}, [
E('button', {
'class': 'btn',
'click': cancelFn
}, [ _('Cancel') ]),
' ',
E('button', {
'class': 'btn primary',
'click': ui.createHandlerFn(this, 'handleApplyConfig', mode, nodes, null)
}, [ _('Import settings') ])
])
]));
window.addEventListener('dragover', handleWindowDragDropIgnore);
window.addEventListener('drop', handleWindowDragDropIgnore);
};
ss.renderSectionAdd = function(/* ... */) {
const nodes = this.super('renderSectionAdd', arguments);
nodes.appendChild(E('button', {
'class': 'btn',
'click': ui.createHandlerFn(this, 'handleConfigImport', 'peer')
}, [ _('Import configuration as peer…') ]));
return nodes;
};
ss.renderSectionPlaceholder = function() {
return E('em', _('No peers defined yet.'));
};
o = ss.option(form.Flag, 'disabled', _('Disabled'), _('Enable / Disable peer. Restart amneziawg interface to apply changes.'));
o.editable = true;
o.optional = true;
o.width = '5%';
o = ss.option(form.Value, 'description', _('Description'), _('Optional. Description of peer.'));
o.placeholder = 'My Peer';
o.datatype = 'string';
o.optional = true;
o.width = '30%';
o.textvalue = function(section_id) {
const dis = ss.getOption('disabled'),
pub = ss.getOption('public_key'),
prv = ss.getOption('private_key'),
psk = ss.getOption('preshared_key'),
name = this.cfgvalue(section_id),
key = pub.cfgvalue(section_id);
const desc = [
E('p', [
name ? E('span', [ name ]) : E('em', [ _('Untitled peer') ])
])
];
if (dis.cfgvalue(section_id) == '1')
desc.push(E('span', {
'class': 'ifacebadge',
'data-tooltip': _('AmneziaWG peer is disabled')
}, [
E('em', [ _('Disabled', 'Label indicating that AmneziaWG peer is disabled') ])
]), ' ');
if (!key || !pub.isValid(section_id)) {
desc.push(E('span', {
'class': 'ifacebadge',
'data-tooltip': _('Public key is missing')
}, [
E('em', [ _('Key missing', 'Label indicating that AmneziaWG peer lacks public key') ])
]));
}
else {
desc.push(
E('span', {
'class': 'ifacebadge',
'data-tooltip': _('Public key: %h', 'Tooltip displaying full AmneziaWG peer public key').format(key)
}, [
E('code', [ key.replace(/^(.{5}).+(.{6})$/, '$1…$2') ])
]),
' ',
(prv.cfgvalue(section_id) && prv.isValid(section_id))
? E('span', {
'class': 'ifacebadge',
'data-tooltip': _('Private key present')
}, [ _('Private', 'Label indicating that AmneziaWG peer private key is stored') ]) : '',
' ',
(psk.cfgvalue(section_id) && psk.isValid(section_id))
? E('span', {
'class': 'ifacebadge',
'data-tooltip': _('Preshared key in use')
}, [ _('PSK', 'Label indicating that AmneziaWG peer uses a PSK') ]) : ''
);
}
return E([], desc);
};
function handleKeyChange(ev, section_id, value) {
const prv = this.section.getUIElement(section_id, 'private_key'),
btn = this.map.findElement('.btn.qr-code');
btn.disabled = (!prv.isValid() || !prv.getValue());
}
o = ss.option(form.Value, 'public_key', _('Public Key'), _('Required. Public key of the AmneziaWG peer.'));
o.modalonly = true;
o.validate = validateBase64;
o.onchange = handleKeyChange;
o = ss.option(form.Value, 'private_key', _('Private Key'), _('Optional. Private key of the AmneziaWG peer. The key is not required for establishing a connection but allows generating a peer configuration or QR code if available. It can be removed after the configuration has been exported.'));
o.modalonly = true;
o.validate = validateBase64;
o.onchange = handleKeyChange;
o.password = true;
o = ss.option(cbiKeyPairGenerate, '_gen_peer_keypair', ' ');
o.modalonly = true;
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.'));
o.modalonly = true;
o.validate = validateBase64;
o.password = true;
o = ss.option(form.DummyValue, '_gen_psk', ' ');
o.modalonly = true;
o.cfgvalue = function(section_id, value) {
return E('button', {
'class': 'btn',
'click': ui.createHandlerFn(this, function(section_id, ev) {
const psk = this.section.getUIElement(section_id, 'preshared_key'),
map = this.map;
return generatePsk().then(function(key) {
psk.setValue(key);
map.save(null, true);
});
}, section_id)
}, [ _('Generate preshared key') ]);
};
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."));
o.datatype = 'ipaddr';
o.textvalue = function(section_id) {
const ips = L.toArray(this.cfgvalue(section_id)),
list = [];
for (let i = 0; i < ips.length; i++) {
if (i > 7) {
list.push(E('em', {
'class': 'ifacebadge cbi-tooltip-container'
}, [
_('+ %d more', 'Label indicating further amount of allowed ips').format(ips.length - i),
E('span', {
'class': 'cbi-tooltip'
}, [
E('ul', ips.map(function(ip) {
return E('li', [
E('span', { 'class': 'ifacebadge' }, [ ip ])
]);
}))
])
]));
break;
}
list.push(E('span', { 'class': 'ifacebadge' }, [ ips[i] ]));
}
if (!list.length)
list.push('*');
return E('span', { 'style': 'display:inline-flex;flex-wrap:wrap;gap:.125em' }, list);
};
o = ss.option(form.Flag, 'route_allowed_ips', _('Route Allowed IPs'), _('Optional. Create routes for Allowed IPs for this peer.'));
o.modalonly = true;
o = ss.option(form.Value, 'endpoint_host', _('Endpoint Host'), _('Optional. Host of peer. Names are resolved prior to bringing up the interface.'));
o.placeholder = 'vpn.example.com';
o.datatype = 'host';
o.textvalue = function(section_id) {
const host = this.cfgvalue(section_id),
port = this.section.cfgvalue(section_id, 'endpoint_port');
return (host && port)
? '%h:%d'.format(host, port)
: (host
? '%h:*'.format(host)
: (port
? '*:%d'.format(port)
: '*'));
};
o = ss.option(form.Value, 'endpoint_port', _('Endpoint Port'), _('Optional. Port of peer.'));
o.modalonly = true;
o.placeholder = '51820';
o.datatype = 'port';
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. A range such as 20-30 is also accepted.'));
o.modalonly = true;
o.validate = validateU16Range;
o.placeholder = '0';
o = ss.option(form.DummyValue, '_keyops', _('Configuration Export'),
_('Generates a configuration suitable for import on a AmneziaWG peer'));
o.modalonly = true;
o.createPeerConfig = function(section_id, endpoint, ips, eips, dns) {
const pub = s.formvalue(s.section, 'public_key'),
port = s.formvalue(s.section, 'listen_port') || '51820',
jc = s.formvalue(s.section, 'awg_jc'),
jmin = s.formvalue(s.section, 'awg_jmin'),
jmax = s.formvalue(s.section, 'awg_jmax'),
s1 = s.formvalue(s.section, 'awg_s1'),
s2 = s.formvalue(s.section, 'awg_s2'),
s3 = s.formvalue(s.section, 'awg_s3'),
s4 = s.formvalue(s.section, 'awg_s4'),
h1 = s.formvalue(s.section, 'awg_h1'),
h2 = s.formvalue(s.section, 'awg_h2'),
h3 = s.formvalue(s.section, 'awg_h3'),
h4 = s.formvalue(s.section, 'awg_h4'),
i1 = s.formvalue(s.section, 'awg_i1'),
i2 = s.formvalue(s.section, 'awg_i2'),
i3 = s.formvalue(s.section, 'awg_i3'),
i4 = s.formvalue(s.section, 'awg_i4'),
i5 = s.formvalue(s.section, 'awg_i5'),
hpk = s.formvalue(s.section, 'awg_header_protection_key'),
cpa = s.formvalue(s.section, 'awg_content_padding_addition'),
rat = s.formvalue(s.section, 'awg_rekey_after_time'),
rt = s.formvalue(s.section, 'awg_rekey_timeout'),
rjat = s.formvalue(s.section, 'awg_reject_after_time'),
kt = s.formvalue(s.section, 'awg_keepalive_timeout'),
mha = s.formvalue(s.section, 'awg_max_handshake_attempts'),
rtr = s.formvalue(s.section, 'awg_random_trailers'),
dc = s.formvalue(s.section, 'awg_disable_cookies'),
prv = this.section.formvalue(section_id, 'private_key'),
psk = this.section.formvalue(section_id, 'preshared_key'),
eport = this.section.formvalue(section_id, 'endpoint_port'),
keep = this.section.formvalue(section_id, 'persistent_keepalive');
// If endpoint is IPv6 we must escape it with []
if (endpoint.indexOf(':') > 0) {
endpoint = '['+endpoint+']';
}
return [
'[Interface]',
'PrivateKey = ' + prv,
eips && eips.length ? 'Address = ' + eips.join(', ') : '# Address not defined',
eport ? 'ListenPort = ' + eport : '# ListenPort not defined',
dns && dns.length ? 'DNS = ' + dns.join(', ') : '# DNS not defined',
jc ? 'Jc = ' + jc : '# Jc not defined',
jmin ? 'Jmin = ' + jmin : '# Jmin not defined',
jmax ? 'Jmax = ' + jmax : '# Jmax not defined',
s1 ? 'S1 = ' + s1 : '# S1 not defined',
s2 ? 'S2 = ' + s2 : '# S2 not defined',
s3 ? 'S3 = ' + s3 : '# S3 not defined',
s4 ? 'S4 = ' + s4 : '# S4 not defined',
h1 ? 'H1 = ' + h1 : '# H1 not defined',
h2 ? 'H2 = ' + h2 : '# H2 not defined',
h3 ? 'H3 = ' + h3 : '# H3 not defined',
h4 ? 'H4 = ' + h4 : '# H4 not defined',
i1 ? 'I1 = ' + i1 : '# I1 not defined',
i2 ? 'I2 = ' + i2 : '# I2 not defined',
i3 ? 'I3 = ' + i3 : '# I3 not defined',
i4 ? 'I4 = ' + i4 : '# I4 not defined',
i5 ? 'I5 = ' + i5 : '# I5 not defined',
hpk ? 'HeaderProtectionKey = ' + hpk : '# HeaderProtectionKey not defined',
cpa ? 'ContentPaddingAddition = ' + cpa : '# ContentPaddingAddition not defined',
rat ? 'RekeyAfterTime = ' + rat : '# RekeyAfterTime not defined',
rt ? 'RekeyTimeout = ' + rt : '# RekeyTimeout not defined',
rjat ? 'RejectAfterTime = ' + rjat : '# RejectAfterTime not defined',
kt ? 'KeepaliveTimeout = ' + kt : '# KeepaliveTimeout not defined',
mha ? 'MaxHandshakeAttempts = ' + mha : '# MaxHandshakeAttempts not defined',
rtr == '1' ? 'RandomTrailers = on' : '# RandomTrailers not defined',
dc == '1' ? 'DisableCookies = on' : '# DisableCookies not defined',
'',
'[Peer]',
'PublicKey = ' + pub,
psk ? 'PresharedKey = ' + psk : '# PresharedKey not used',
ips && ips.length ? 'AllowedIPs = ' + ips.join(', ') : '# AllowedIPs not defined',
endpoint ? 'Endpoint = ' + endpoint + ':' + port : '# Endpoint not defined',
keep ? 'PersistentKeepAlive = ' + keep : '# PersistentKeepAlive not defined'
].join('\n');
};
o.handleGenerateQR = function(section_id, ev) {
const mapNode = ss.getActiveModalMap(),
headNode = mapNode.parentNode.querySelector('h4'),
configGenerator = this.createPeerConfig.bind(this, section_id),
parent = this.map,
eips = this.section.formvalue(section_id, 'allowed_ips');
return Promise.all([
network.getWANNetworks(),
network.getWAN6Networks(),
network.getNetwork('lan'),
L.resolveDefault(uci.load('ddns')),
L.resolveDefault(uci.load('system')),
parent.save(null, true)
]).then(function(data) {
const hostnames = [];
uci.sections('ddns', 'service', function(s) {
if (typeof(s?.lookup_host) == 'string' && s?.enabled == '1')
hostnames.push(s.lookup_host);
});
uci.sections('system', 'system', function(s) {
if (typeof(s?.hostname) == 'string' && s?.hostname?.indexOf('.') > 0)
hostnames.push(s.hostname);
});
for (let i = 0; i < data[0].length; i++)
hostnames.push.apply(hostnames, data[0][i].getIPAddrs().map(function(ip) { return ip.split('/')[0] }));
for (let i = 0; i < data[1].length; i++)
hostnames.push.apply(hostnames, data[1][i].getIP6Addrs().map(function(ip) { return ip.split('/')[0] }));
const ips = [ '0.0.0.0/0', '::/0' ];
const dns = [];
const lan = data[2];
if (lan) {
const lanIp = lan.getIPAddr();
if (lanIp) {
dns.unshift(lanIp)
}
}
const qrm = new form.JSONMap({ config: { endpoint: hostnames[0], allowed_ips: ips, addresses: eips, dns_servers: dns } }, null, _('The generated configuration can be imported into a WireGuard client application to set up a connection towards this device.'));
qrm.parent = parent;
const qrs = qrm.section(form.NamedSection, 'config');
let qro;
function handleConfigChange(ev, section_id, value) {
const code = this.map.findElement('.qr-code'),
conf = this.map.findElement('.client-config'),
endpoint = this.section.getUIElement(section_id, 'endpoint'),
ips = this.section.getUIElement(section_id, 'allowed_ips'),
eips = this.section.getUIElement(section_id, 'addresses'),
dns = this.section.getUIElement(section_id, 'dns_servers');
if (this.isValid(section_id)) {
conf.firstChild.data = configGenerator(endpoint.getValue(), ips.getValue(), eips.getValue(), dns.getValue());
code.style.opacity = '.5';
buildSVGQRCode(conf.firstChild.data, code);
}
};
qro = qrs.option(form.Value, 'endpoint', _('Connection endpoint'), _('The public hostname or IP address of this system the peer should connect to. This usually is a static public IP address, a static hostname or a DDNS domain.'));
qro.datatype = 'or(ipaddr,hostname)';
hostnames.forEach(function(hostname) { qro.value(hostname) });
qro.onchange = handleConfigChange;
qro = qrs.option(form.DynamicList, 'allowed_ips', _('Allowed IPs'), _('IP addresses that are allowed inside the tunnel. The peer will accept tunnelled packets with source IP addresses matching this list and route back packets with matching destination IP.'));
qro.datatype = 'ipaddr';
qro.default = ips;
ips.forEach(function(ip) { qro.value(ip) });
qro.onchange = handleConfigChange;
qro = qrs.option(form.DynamicList, 'dns_servers', _('DNS Servers'), _('DNS servers for the remote clients using this tunnel to your openwrt device. Some wireguard clients require this to be set.'));
qro.datatype = 'ipaddr';
qro.default = dns;
qro.onchange = handleConfigChange;
qro = qrs.option(form.DynamicList, 'addresses', _('Addresses'), _('IP addresses for the peer to use inside the tunnel. Some clients require this setting.'));
qro.datatype = 'ipaddr';
qro.default = eips;
eips.forEach(function(eip) { qro.value(eip) });
qro.onchange = handleConfigChange;
qro = qrs.option(form.DummyValue, 'output');
qro.renderWidget = function() {
const peer_config = configGenerator(hostnames[0], ips, eips, dns);
const node = E('div', {
'style': 'display:flex;flex-wrap:wrap;align-items:center;gap:.5em;width:100%'
}, [
E('div', {
'class': 'qr-code',
'style': 'text-align:center'
}, [
E('em', { 'class': 'spinning' }, [ _('Generating QR code…') ])
]),
E('pre', {
'class': 'client-config',
'style': 'flex:1;white-space:pre;overflow:auto',
'click': function(ev) {
const sel = window.getSelection(),
range = document.createRange();
range.selectNodeContents(ev.currentTarget);
sel.removeAllRanges();
sel.addRange(range);
}
}, [ peer_config ])
]);
buildSVGQRCode(peer_config, node.firstChild);
return node;
};
return qrm.render().then(function(nodes) {
mapNode.classList.add('hidden');
mapNode.nextElementSibling.classList.add('hidden');
headNode.appendChild(E('span', [ ' » ', _('Generate configuration') ]));
mapNode.parentNode.appendChild(E([], [
nodes,
E('div', {
'class': 'right'
}, [
E('button', {
'class': 'btn',
'click': function() {
nodes.parentNode.removeChild(nodes.nextSibling);
nodes.parentNode.removeChild(nodes);
mapNode.classList.remove('hidden');
mapNode.nextSibling.classList.remove('hidden');
headNode.removeChild(headNode.lastChild);
}
}, [ _('Back to peer configuration') ])
])
]));
if (!s.formvalue(s.section, 'listen_port')) {
nodes.appendChild(E('div', { 'class': 'alert-message' }, [
E('p', [
_('No fixed interface listening port defined, peers might not be able to initiate connections to this AmneziaWG instance!')
])
]));
}
});
});
};
o.cfgvalue = function(section_id, value) {
const privkey = this.section.cfgvalue(section_id, 'private_key');
return E('button', {
'class': 'btn qr-code',
'style': 'display:inline-flex;align-items:center;gap:.5em',
'click': ui.createHandlerFn(this, 'handleGenerateQR', section_id),
'disabled': privkey ? null : ''
}, [
Object.assign(E(qrIcon), { style: 'width:22px;height:22px' }),
_('Generate configuration…')
]);
};
},
deleteConfiguration: function() {
uci.sections('network', 'amneziawg_%s'.format(this.sid), function(s) {
uci.remove('network', s['.name']);
});
}
});