97 lines
2.8 KiB
JavaScript
97 lines
2.8 KiB
JavaScript
// 13 b4 37 XX XX XX XX > (pk) - Authenticated
|
|
// 13 37 > (pk) - I am <...>
|
|
// e7 5a 3d ed > (gk) - Authenticate yourself
|
|
// 55 44 e9 37 < (pk) - Forget me
|
|
// e7 5a 3d ea > (pk) - Forget me. OK
|
|
|
|
const dgram = require('dgram');
|
|
const net = require('net');
|
|
const { Tun } = require('tuntap2');
|
|
const { encrypt, decrypt } = require('../encryption');
|
|
const IP = require('ip-packet');
|
|
|
|
const conns = {};
|
|
const ips = {};
|
|
const ports = {};
|
|
|
|
const sock = dgram.createSocket('udp4');
|
|
|
|
const l = new net.BlockList();
|
|
l.addSubnet(config.subnet, config.len);
|
|
|
|
const tun = new Tun();
|
|
|
|
tun.mtu = config.mtu;
|
|
tun.ipv4 = `${config.addr}/${config.len}`;
|
|
tun.isUp = true;
|
|
|
|
tun.on('data', (buff) => {
|
|
if (buff[0] >> 4 !== 4) return;
|
|
const p = IP.decode(buff);
|
|
//(p);
|
|
const user = Object.values(config.users).find(x => x.addr == p.destinationIp);
|
|
//(user);
|
|
if (!user) return;
|
|
const targetIp = ips[user.username];
|
|
const targetPort = ports[user.username];
|
|
//(targetIp, targetPort);
|
|
if (!targetIp || !targetPort) return;
|
|
sock.send(encrypt(IP.encode(p), user.key, config.iv, config.algorithm), targetPort, targetIp);
|
|
})
|
|
|
|
sock.on('listening', () => {
|
|
const a = sock.address();
|
|
console.log(`Listening on ${a.address}:${a.port}`);
|
|
});
|
|
|
|
sock.on('message', (msg, info) => {
|
|
var dec;
|
|
var uname;
|
|
var acc;
|
|
for (const un in config.users) {
|
|
const u = config.users[un];
|
|
dec = decrypt(msg, u.key, config.iv, config.algorithm);
|
|
if (dec.length != 0) {
|
|
uname = un;
|
|
acc = u;
|
|
break;
|
|
}
|
|
}
|
|
ips[uname] = info.address;
|
|
ports[uname] = info.port;
|
|
//const dec = decrypt(msg, acc.key, config.iv, config.algorithm);
|
|
//(dec);
|
|
if (dec.length == 0) {
|
|
console.error(`Empty or malformed packet from ${uname}`);
|
|
return;
|
|
}
|
|
if (dec.length == 2 && dec[0] == 0x13 && dec[1] == 0x37) {
|
|
const spl = acc.addr.split('.').map(s => parseInt(s));
|
|
const buff = Buffer.from([
|
|
0x13,
|
|
0xb4,
|
|
0x37,
|
|
...spl
|
|
]);
|
|
const enc = encrypt(buff, acc.key, config.iv, config.algorithm);
|
|
sock.send(enc, info.port, info.address);
|
|
return;
|
|
}
|
|
|
|
if ((dec[0] >> 4) !== 4) return;
|
|
const packet = IP.decode(dec);
|
|
//(packet);
|
|
packet.sourceIp = acc.addr;
|
|
if ((config.allow_outbound && !l.check(packet.destinationIp)) || packet.destinationIp == config.addr) {
|
|
tun.write(dec);
|
|
return;
|
|
}
|
|
const user = Object.values(config.users).find(x => x.addr == packet.destinationIp);
|
|
if (!user) return;
|
|
const targetIp = ips[user.username];
|
|
const targetPort = ports[user.username];
|
|
if (!targetIp || !targetPort) return;
|
|
sock.send(encrypt(dec, user.key, config.iv, config.algorithm), targetPort, targetIp);
|
|
});
|
|
|
|
sock.bind(config.port); |