103 lines
2.7 KiB
JavaScript
103 lines
2.7 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 { randomFill, randomFillSync } = require('crypto');
|
|
const sock = dgram.createSocket('udp4');
|
|
|
|
const tun = new Tun();
|
|
|
|
var established = false;
|
|
|
|
sock.on('message', (msg, info) => {
|
|
const pd = decrypt(msg, config.privateKey, config.iv, config.algorithm);
|
|
const gd = decrypt(msg, config.globalKey, config.iv, config.algorithm);
|
|
const dec = pd.length == 0 ? gd : pd;
|
|
if (dec.length == 4 && dec[0] == 0xe7 && dec[1] == 0x5a && dec[2] == 0x3d && dec[3] == 0xed) {
|
|
console.log(`Server asks to authenticate. Authenticating...`);
|
|
authenticateAndCheck();
|
|
return;
|
|
}
|
|
if (dec.length == 7 && dec[0] == 0x13 && dec[1] == 0xb4 && dec[2] == 0x37) {
|
|
const ip = dec.slice(3);
|
|
const strIp = ip.map(s => s.toString()).join('.');
|
|
console.log(`My IP: ${strIp}`);
|
|
tun.mtu = config.mtu;
|
|
tun.ipv4 = `${strIp}/${config.len}`;
|
|
tun.isUp = true;
|
|
tun.on('data', (d) => {
|
|
sock.send(
|
|
encrypt(
|
|
d,
|
|
config.privateKey,
|
|
config.iv,
|
|
config.algorithm
|
|
),
|
|
config.port,
|
|
config.endpoint
|
|
);
|
|
});
|
|
established = true;
|
|
}
|
|
if (established && (dec[0] >> 4 == 4)) {
|
|
tun.write(dec);
|
|
}
|
|
});
|
|
|
|
function authenticate() {
|
|
sock.send(
|
|
encrypt(
|
|
Buffer.from([
|
|
0x13, 0x37
|
|
]),
|
|
config.privateKey,
|
|
config.iv,
|
|
config.algorithm
|
|
),
|
|
config.port,
|
|
config.endpoint
|
|
);
|
|
}
|
|
|
|
function authenticateAndCheck() {
|
|
authenticate();
|
|
|
|
var i = setInterval(() => {
|
|
if (!established) {
|
|
console.log(`Connection not established. Authenticating again...`);
|
|
authenticate();
|
|
} else {
|
|
clearInterval(i);
|
|
console.log(`Authenticated.`);
|
|
}
|
|
}, 2000);
|
|
}
|
|
|
|
function keepAlive() {
|
|
var buff = Buffer.alloc(64);
|
|
randomFillSync(buff);
|
|
buff[0] = 0x60; // actually you can send anything just make sure that buff[0] >> 4 !== 4
|
|
sock.send(
|
|
encrypt(
|
|
buff,
|
|
config.privateKey,
|
|
config.iv,
|
|
config.algorithm
|
|
),
|
|
config.port,
|
|
config.endpoint
|
|
);
|
|
}
|
|
|
|
authenticateAndCheck();
|
|
|
|
setInterval(() => {
|
|
keepAlive();
|
|
}, 15000); |