FearlessVPNNG/server/index.js

110 lines
3.2 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.length == 4 &&
dec[0] == 0x55 && dec[1] == 0x44 && dec[2] == 0xe9 && dec[3] == 0x37) {
const buff = Buffer.from([
0xe7,
0x5a,
0x3d,
0xea
]);
const enc = encrypt(buff, acc.key, config.iv, config.algorithm);
sock.send(enc, info.port, info.address);
delete conns[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);