-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnfsense.js
2651 lines (2608 loc) · 135 KB
/
nfsense.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
script = {
setup: function () {
console.log("setting permissions");
cp.execSync("chmod 770 " + path.app + " -R");
console.log("updating package list...");
try { cp.execSync("apt-get update"); } catch (e) { }
console.log("installing system network packages...");
cp.execSync("apt-get install -y conntrack nftables isc-dhcp-server bind9 dnsmasq psmisc bmon bpytop tcptrack openvpn wireguard traceroute");
console.log("installing NPM packages...");
cp.execSync("cd " + path.app + " ; npm i express");
cp.execSync("cd " + path.app + " ; npm i ws");
cp.execSync("cd " + path.app + " ; npm i systeminformation");
if (cfg.services.telegram.enabled)
cp.execSync("cd " + path.app + " ; npm i node-telegram-bot-api");
console.log("checking if packet forwarding is enabled");
if (fs.readFileSync("/proc/sys/net/ipv4/ip_forward", 'utf8').includes("0")) {
console.log("forwarding not enabled!! Enabling now");
cp.execSync(" sudo sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/' /etc/sysctl.conf");
cp.execSync("echo 1 | sudo tee /proc/sys/net/ipv4/ip_forward");
cp.execSync("sudo sysctl -p");
} else console.log("kernel forwarding is enabled");
console.log("checking nfTables server...");
if (!fs.existsSync('/etc/systemd/system/sysinit.target.wants/nftables.service')) {
cp.execSync("systemctl enable nftables.service");
console.log("enabling now");
//needed if have bridge
// cp.execSync("sudo sed 's`Wants=network-pre.target`#Wants=network-pre.target`' /etc/systemd/system/sysinit.target.wants/nftables.service >tmp");
// cp.execSync("sudo mv tmp /etc/systemd/system/sysinit.target.wants/nftables.service");
// cp.execSync("sudo sed 's`Before=network-pre.target shutdown.target`After=network.target' /etc/systemd/system/sysinit.target.wants/nftables.service >tmp");
// cp.execSync("sudo mv tmp /etc/systemd/system/sysinit.target.wants/nftables.service");
}
else console.log("already enabled");
console.log("disabling SystemD Bind9");
cp.execSync("systemctl stop named.service");
cp.execSync("systemctl disable named.service");
console.log("disabling SystemD DNSmasq");
cp.execSync("systemctl stop dnsmasq.service");
cp.execSync("systemctl disable dnsmasq.service");
console.log("disabling SystemD ISC-DHCP-Server");
cp.execSync("systemctl stop isc-dhcp-server.service");
cp.execSync("systemctl disable isc-dhcp-server.service");
try { cp.execSync("mkdir " + path.app + "/tmp"); } catch { }
console.log("\n\nrouter setup done!!\n");
process.exit();
},
gatewayMonitor: function () {
for (let x = 0; x < cfg.gateways.length; x++) {
let gateway = state.gateways[x], config = cfg.gateways[x], lostLan = 0, lostLanPercent = 0, averageLan = 0, averageLanCalc = 0,
lostWan = 0, lostWanPercent = 0, averageWan = 0, wanTotalSamples = cfg.monitor.wan.samples * cfg.monitor.wan.targets.length
, averageWanTally = wanTotalSamples, averageWanCalc = 0;
if (cfg.monitor.lan.enable == true) {
if (state.gateways[cfg.gateways.length - 1].sampleLAN.length == cfg.monitor.lan.samples) {
if (gateway.sampleWAN[cfg.monitor.wan.targets.length - 1].length == cfg.monitor.wan.samples) start();
}
} else if (gateway.sampleWAN[cfg.monitor.wan.targets.length - 1].length == cfg.monitor.wan.samples) start();
function start() {
if (state.boot == false) {
if (x == cfg.gateways.length - 1) state.boot = true;
return;
} else discover();
}
function discover() {
for (let y = 0; y < cfg.monitor.lan.samples; y++) {
if (gateway.sampleLAN[y] === false) lostLan++;
else averageLan += gateway.sampleLAN[y];
}
for (let y = 0; y < cfg.monitor.wan.targets.length; y++) {
for (let z = 0; z < cfg.monitor.wan.samples; z++) {
if (gateway.sampleWAN[y][z] != false) {
averageWan += gateway.sampleWAN[y][z];
} else {
averageWanTally--;
lostWan++;
}
}
lostLanPercent = Math.floor((lostLan / cfg.monitor.lan.samples) * 100);
lostWanPercent = Math.floor((lostWan / wanTotalSamples) * 100);
averageLanCalc = Math.floor(averageLan / cfg.monitor.lan.samples);
averageWanCalc = Math.floor(averageWan / averageWanTally);
gateway.pingAverageWAN = averageWanCalc;
gateway.pingAverageLAN = averageLanCalc;
}
gateway.results = {
lanLatency: averageLanCalc, lanLoss: lostLanPercent, wanLatency: averageWanCalc
, wanLoss: lostWanPercent, wanSamples: wanTotalSamples, lost: lostWan, pingTotal: averageWan, responses: averageWanTally,
};
if (lostLanPercent >= cfg.monitor.lan.lossError) { gateway.status = "offline-LAN loss"; gateway.offline = true; }
else if (cfg.monitor.lan.lossWarn != undefined && lostLanPercent >= cfg.monitor.lan.lossWarn) gateway.status = "DEG-LLoss";
else if (averageLanCalc >= cfg.monitor.lan.latencyError) { gateway.status = "offline-LAN latency"; gateway.offline = true; }
else if (cfg.monitor.lan.latencyWarn - undefined && averageLanCalc >= cfg.monitor.lan.latencyWarn) gateway.status = "DEG-LLate";
else if (lostWanPercent >= cfg.monitor.wan.lossError) { gateway.status = "offline-WAN loss"; gateway.offline = true; }
else if (cfg.monitor.wan.lossWarn != undefined && lostWanPercent >= cfg.monitor.wan.lossWarn) gateway.status = "DEG-WLoss";
else if (averageWanCalc >= cfg.monitor.wan.latencyError) { gateway.status = "offline-WAN latency"; gateway.offline = true; }
else if (cfg.monitor.wan.latencyWarn != undefined && averageWanCalc >= cfg.monitor.wan.latencyWarn) gateway.status = "DEG-WLate";
else gateway.status = "online";
report();
}
function report() {
if (gateway.statusPrevious != gateway.status) {
if (gateway.statusPrevious == "online") gateway.timer = time.epoch;
if (gateway.status == "online" && gateway.statusPrevious != undefined) {
if (time.epoch - gateway.timer >= (cfg.monitor.reconnect)) {
console.log("gateway - " + config.name + " - " + gateway.status + " - " + (cfg.monitor.lan.enable ? "LAN average: " + averageLanCalc
+ " LAN loss: " + lostLanPercent + "%, " : "") + "WAN Average: " + averageWanCalc + " WAN Loss: "
+ lostWanPercent + "%" + ((gateway.statusPrevious.includes("offline")) ? " - Was offline for " : " - Was degraded for ")
+ (time.epoch - gateway.timer) + " seconds");
}
} else {
console.log("gateway - " + config.name + " - " + gateway.status + " - " + (cfg.monitor.lan.enable ? "LAN average:" + averageLanCalc
+ " LAN loss: " + lostLanPercent + "%, " : "") + "WAN Average: " + averageWanCalc + " WAN Loss: " + lostWanPercent + "%");
}
if (gateway.status.includes("online") && gateway.offline == true || gateway.statusPrevious == undefined
|| gateway.status.includes("offline")) {
if (gateway.status == "online") gateway.offline = false;
clearTimeout(state.nfTables.timer);
state.nfTables.timer = setTimeout(() => { script.mangle(); }, 3e3);
}
gateway.statusPrevious = gateway.status;
}
}
}
},
pingLan: function () {
let wait = 0;
for (let x = 0; x < cfg.gateways.length; x++) {
setTimeout(() => {
// console.log("pinging wan " + cfg.gateways[x].name + " (" + cfg.gateways[x].ip
// + ") with mark: " + (x + 1));
app.pingAsync(cfg.gateways[x].ip, state.gateways[x].sampleLAN, state.sampleLAN, 0);
if (x == cfg.gateways.length - 1) {
if (state.sampleLAN < cfg.monitor.lan.samples - 1) state.sampleLAN++;
else state.sampleLAN = 0;
setTimeout(() => { script.pingLan(); }, cfg.monitor.lan.interval * 1e3);
}
}, wait);
wait += cfg.monitor.lan.delay;
}
},
pingWan: function () {
let wait = 0;
for (let x = 0; x < cfg.gateways.length; x++) {
for (let y = 0; y < cfg.monitor.wan.targets.length; y++) {
setTimeout(() => {
// console.log("pinging wan " + cfg.gateways[x].name + " (" + cfg.monitor.wan.targets[y]
// + ") with mark: " + (x + 1));
app.pingAsync(cfg.monitor.wan.targets[y], state.gateways[x].sampleWAN[y], state.sampleWAN, (x + 1));
if (x == cfg.gateways.length - 1 && y == cfg.monitor.wan.targets.length - 1) {
if (state.sampleWAN < cfg.monitor.wan.samples - 1) state.sampleWAN++;
else state.sampleWAN = 0;
setTimeout(() => { script.pingWan(); }, cfg.monitor.wan.interval * 1e3);
}
}, wait);
wait += cfg.monitor.wan.delay;
}
}
},
pingWanRound: function () {
let wait = 0;
for (let y = 0; y < cfg.monitor.wan.targets.length; y++) {
for (let x = 0; x < cfg.gateways.length; x++) {
setTimeout(() => {
// console.log("pinging wan " + cfg.gateways[x].name + " (" + cfg.monitor.wan.targets[y]
// + ") with mark: " + (x + 1));
app.pingAsync(cfg.monitor.wan.targets[y], state.gateways[x].sampleWAN[y], state.sampleWAN, (x + 1));
if (x == cfg.gateways.length - 1 && y == cfg.monitor.wan.targets.length - 1) {
if (state.sampleWAN < cfg.monitor.wan.samples - 1) state.sampleWAN++;
else state.sampleWAN = 0;
setTimeout(() => { script.pingWanRound(); }, cfg.monitor.wan.interval * 1e3);
}
}, wait);
wait += cfg.monitor.wan.delay;
}
}
},
mangle: function () {
let sequence = [], sequenceAll = [], set = [], numgen = [];
for (let x = 0; x < state.gateways.length; x++) {
// console.log(state.gateways[x].status)
if (cfg.network.gateway.startAll) {
if (state.gateways[x].status == undefined
|| state.gateways[x].status.includes("offline") == false) sequence.push(x);
} else if (state.gateways[x].status.includes("offline") == false) sequence.push(x);
sequenceAll.push([x]);
}
switch (cfg.network.gateway.mode) {
case "teaming":
if (cfg.network.gateway.weighted == true) {
let weights;
numgen = { mode: "random", mod: 100, offset: 0 };
if (sequence.length == 0) {
if (cfg.network.gateway.failAll == false) { set = [[99, 0]]; }
else {
weights = script.calcWeight(sequenceAll);
for (let x = 0; x < sequenceAll.length; x++)
set.push([{ range: [weights[x].start, weights[x].end] }, (sequenceAll + 1)])
}
} else {
weights = script.calcWeight(sequence);
for (let x = 0; x < sequence.length; x++)
set.push([{ range: [weights[x].start, weights[x].end] }, (sequence[x] + 1)])
}
} else {
if (sequence.length == 0) {
console.log("gateway - teaming - all gateways are offline")
if (cfg.network.gateway.failAll == false) {
console.log("gateway - teaming - mangle set to first gateway only")
numgen = { mode: "inc", mod: 1, offset: 0 }
set = [[0, 1]];
}
else {
console.log("gateway - teaming - mangle set to all gateways")
numgen = { mode: "inc", mod: sequenceAll.length, offset: 0 }
for (let x = 0; x < sequenceAll.length; x++)
set.push([x, sequenceAll[x] + 1]);
}
} else {
numgen = { mode: "inc", mod: sequence.length, offset: 0 }
for (let x = 0; x < sequence.length; x++)
set.push([x, sequence[x] + 1]);
}
}
nftWrite();
break;
case "failover":
for (let x = 0; x < state.gateways.length; x++) {
let gateway = state.gateways[x];
if (state.gatewaySelected == undefined) {
if (gateway.status === undefined || gateway.status.includes("online")) { switchGateway(gateway, x); break; }
} else if (state.gatewaySelected !== x) {
if (state.gateways[state.gatewaySelected].offline == true) {
switchGateway(gateway, x); break;
} else if (x < state.gatewaySelected && gateway.status.includes("online")) {
switchGateway(gateway, x); break;
}
}
}
function switchGateway(gateway, x) {
console.log("gateway - failover - selecting gateway " + cfg.gateways[x].name);
let interface = gateway.interface || cfg.network.interface[1]
? cfg.network.interface[1].if : cfg.network.interface[0].if;
if (cfg.gateways[x].allowedIPs != undefined && cfg.gateways[x].allowedIPs.length > 0) {
console.log("gateway - failover - applying NAT restricted access");
nft.update('nat postrouting', 'masquerade', 'ip saddr {' + cfg.gateways[x].allowedIPs
+ '} oif "' + interface + '" masquerade');
} else if (cfg.services.portal.enabled) {
nft.update('nat postrouting', 'masquerade', 'ip saddr @allow oif "' + interface + '" masquerade');
} else {
nft.update("nat postrouting", "masquerade", 'ip saddr ' + cfg.network.interface[0].subnetCIDR[0] + '/'
+ cfg.network.interface[0].subnetCIDR[1] + ' oif "' + interface + '" masquerade');
}
try { cp.execSync("ip route delete default"); } catch { }
try { cp.execSync("ip route add default via " + cfg.gateways[x].ip); } catch { }
if (cfg.vpn.wireguard.client && cfg.vpn.wireguard.client.length > 0) app.vpn.wireguard.clientConnect();
state.gatewaySelected = x;
}
break;
}
function nftWrite() {
app.nft.tables.mangle[2].rule.expr[2].mangle.value.map.key.numgen = numgen;
app.nft.tables.mangle[2].rule.expr[2].mangle.value.map.data.set = set;
function parseIPSubnets(input) {
const pairs = input.split(", ").map(pair => pair.trim());
return pairs.map(pair => {
const [ip, subnet] = pair.split("/");
return { ip, subnet: parseInt(subnet, 10) };
});
}
if (state.nfTables.mangle == undefined) {
nftCreateTable();
} else {
app.nft.tables.mangle[2].rule.handle = state.nfTables.mangle;
console.log("nftables - updating mangle table - ", set);
let command = "printf '" + JSON.stringify({ nftables: [{ replace: app.nft.tables.mangle[2] }] }) + "' | nft -j -f -"
cp.exec(command, (e) => {
if (e) {
console.log("!!!!!!mangle table doesnt exist anymore, nftables must have been flushed!!!!!!")
// console.error(e);
app.nft.create(false);
nftCreateTable();
}
})
}
function nftCreateTable() {
console.log("nftables - creating mangle ruleset");
cp.execSync('nft flush chain ip mangle prerouting');
let mangleNum, rbuf = [];
app.nft.tables.mangle.forEach((e) => { rbuf.push({ add: e }) });
let command = "printf '" + JSON.stringify({ nftables: rbuf }) + "' | nft -j -f -"
cp.execSync(command);
if (cfg.services.portal.enabled) {
console.log("nftables - adding portal disallow rule");
cp.execSync("nft insert rule mangle prerouting ip saddr != @allow return");
}
mangleNum = parse(cp.execSync('nft -a list chain ip mangle prerouting').toString(), 'nfsense_mangle" # handle ', '\n')
console.log("nftables - mangle table rule handle is: " + Number(mangleNum));
state.nfTables.mangle = Number(mangleNum);
}
}
},
checkRoutes: function () {
// cp.execSync("sudo tee -a /etc/iproute2/rt_tables").toString();
let rt_tables = fs.readFileSync("/etc/iproute2/rt_tables", 'utf8');
let ip_rules = cp.execSync("ip rule show").toString();
let routes = "", error = false;
console.log("system - updating routing tables");
for (let x = 0; x < cfg.gateways.length; x++) {
if (rt_tables.includes((x + 1) + " gw" + (x + 1))) { } //console.log("rt_tables includes gateway: " + x);
else {
// console.log("rt_tables doesnt have gateway: " + x + ", creating...");
cp.execSync('echo "' + (x + 1) + ' gw' + (x + 1) + '" | tee -a /etc/iproute2/rt_tables');
}
if (ip_rules.includes("lookup gw" + (x + 1))) { }// console.log("ip_rules includes gateway: " + x);
else {
// console.log("ip_rules doesnt have gateway: " + x + ", creating...");
cp.execSync("ip rule add fwmark " + (x + 1) + " table gw" + (x + 1));
}
// console.log("ip_route re/creating routes for gateway: " + x);
try {
cp.execSync("sudo ip route flush table gw" + (x + 1));
cp.execSync("ip route add default via " + cfg.gateways[x].ip + " table gw" + (x + 1));
cp.execSync("ip route add " + cfg.network.interface[0].subnetCIDR[0] + '/'
+ cfg.network.interface[0].subnetCIDR[1]
+ " dev " + cfg.network.interface[0].if + " table gw" + (x + 1))
} catch {
try {
cp.execSync("ip route add default via " + cfg.gateways[x].ip + " table gw" + (x + 1));
cp.execSync("ip route add " + cfg.network.interface[0].subnetCIDR[0] + '/'
+ cfg.network.interface[0].subnetCIDR[1]
+ " dev " + cfg.network.interface[0].if + " table gw" + (x + 1))
} catch (e) {
// console.log(e);
console.log("setting routes encountered an error, will try again in 5 seconds");
error = true;
}
}
}
if (error) setTimeout(() => {
console.log("trying to set routes again");
script.checkRoutes();
}, 5e3);
},
calcWeight: function (sequence) {
let prep = [];
for (let x = 0; x < sequence.length; x++) prep.push(cfg.gateways[x].weight);
return calc(prep);
function calc(weights) {
const totalShares = 100;
const totalWeight = weights.reduce((acc, weight) => acc + weight, 0);
const shareDistribution = weights.map((weight) =>
Math.floor((weight / totalWeight) * totalShares)
);
let remainingShares = totalShares - shareDistribution.reduce((acc, share) => acc + share, 0);
for (let i = 0; remainingShares > 0; i = (i + 1) % weights.length) {
shareDistribution[i]++;
remainingShares--;
}
let currentStart = 0;
const ranges = shareDistribution.map((share) => {
const start = currentStart;
const end = start + share - 1;
currentStart = end + 1; // Ensure next range starts 1 above the current end
return { start, end };
});
return ranges;
}
},
printStats: function () {
let pbuf = "", gbuf = "";
pbuf += "gateway - Users: " + stat.dhcp.total;
pbuf += " - Total Connections: " + (stat.conntrack.total - 1) + " |";
for (let x = 0; x < cfg.gateways.length; x++)
pbuf += " R" + (x + 1) + ":" + stat.conntrack.gateways[x] + "|";
gbuf = "gateway - Modem Status: |";
for (let x = 0; x < cfg.gateways.length; x++) {
gbuf += cfg.gateways[x].name + " - ";
if (state.gateways.status == undefined || state.gateways.status == "online") gbuf += "ON";
else if (state.gateways.status.includes("offline")) gbuf += "OFF";
else if (state.gateways.status.includes("degraded")) gbuf += "deg";
gbuf += " |";
}
console.log(pbuf);
console.log(gbuf);
},
getStat: function () {
stat_nv.bw = stat_nv.bw || [];
stat_nv.arp = stat_nv.arp || [];
stat_nv.gateways = stat_nv.gateways || { pingDropsWan: [] };
stat_nv.conntrack = stat_nv.conntrack || [];
for (let x = 0; x < cfg.network.interface.length; x++) {
if (!stat_nv.bw[x]) stat_nv.bw.push([[], []])
stat_nv.bw[x][0][time.min10] = stat.bw[x][0];
stat_nv.bw[x][1][time.min10] = stat.bw[x][1];
}
for (let x = 0; x < cfg.gateways.length; x++) {
if (stat_nv.avg5Min.gateways[x] != undefined)
stat_nv.gateways.pingDropsWan[x]
= Math.floor(stat_nv.avg5Min.gateways[x].reduce((a, b) => a + b, 0));
}
stat_nv.conntrack[time.min10]
= Math.floor(stat_nv.avg5Min.conntrack.total.reduce((a, b) => a + b, 0) / 300);
stat_nv.arp[time.min10] = Math.floor(stat_nv.avg5Min.arp.reduce((a, b) => a + b, 0) / 300);
file.write("stat_nv");
},
getStatSec: function () {
stat_nv.step5Min = stat_nv.step5Min || 0;
stat_nv.avg5Min = stat_nv.avg5Min || {};
stat_nv.avg5Min = stat_nv.avg5Min || {};
stat_nv.avg5Min.conntrack = stat_nv.avg5Min.conntrack || {};
stat_nv.avg5Min.conntrack.total = stat_nv.avg5Min.conntrack.total || [];
stat_nv.avg5Min.arp = stat_nv.avg5Min.arp || [];
stat_nv.avg5Min.gateways = stat_nv.avg5Min.gateways || [];
stat_nv.avg5Min.conntrack.total[stat_nv.step5Min] = stat.conntrack.total;
stat_nv.avg5Min.arp[stat_nv.step5Min] = Object.keys(arp).length;
if (stat_nv.step5Min < 299) stat_nv.step5Min++; else stat_nv.step5Min = 0;
},
voucher: {
generate: function (length, count, duration, speed, multi, lowerCase) {
const letters = lowerCase ? 'abcdefghijklmnopqrstuvwxyz' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const numbers = '0123456789';
const charset = letters + numbers;
const result = {};
for (let i = 0; i < count; i++) {
let randomString = '';
randomString += letters[Math.floor(Math.random() * letters.length)];
for (let j = 1; j < length; j++) {
randomString += charset[Math.floor(Math.random() * charset.length)];
}
result[randomString] = { duration: (duration * 60 * 60), speed, multi, created: time.epoch };
}
//const vouchertest = script.voucher.generate(10, 3, 86400, 1, false, true);
console.log("vouchers - creating " + count + " vouchers with a duration of: " + duration + " hours");
console.log(result);
Object.assign(voucher, result);
file.write("voucher");
return result
},
use: function (code, mac) { // runs when someone click submit on portal login page
if (voucher[code] && arp[mac]) {
if (voucher[code].ip != undefined) {
if (voucher[code].multi === false) {
console.log("vouchers - relogin - code: " + code + ", for mac: " + mac + " - clearing old IPs");
script.voucher.nft(voucher[code].ip, voucher[code].speed, "delete");
voucher[code].ip = [arp[mac].ip];
voucher[code].mac = mac;
script.voucher.nft(arp[mac].ip, voucher[code].speed, "add");
} else if (voucher[code].ip.length <= voucher[code].multi) {
console.log("vouchers - relogin - code: " + code + ", for mac: " + mac + " - adding new IP");
script.voucher.nft(voucher[code].ip, voucher[code].speed, "add");
voucher[code].ip.push(arp[mac].ip)
script.voucher.nft(arp[mac].ip, voucher[code].speed, "add");
} else console.log("vouchers - relogin - code: " + code + ", for mac: " + mac + " - no more slots, disallowed");
file.write("voucher");
voucher[code].update = time.epoch;
return true;
} else {
voucher[code].mac = mac;
voucher[code].activated = time.epoch;
voucher[code].update = time.epoch;
voucher[code].ip = [arp[mac].ip];
// console.log(voucher[code])
console.log("vouchers - adding voucher: " + code + ", for mac: " + mac + ", with IP: " + arp[mac].ip
+ " - expires in: " + (voucher[code].duration / 60) + " min");
script.voucher.nft(arp[mac].ip, voucher[code].speed, "add");
file.write("voucher");
return true;
}
} else return false;
},
prune: function () {
for (const code in voucher) {
if (voucher[code] != undefined && voucher[code].activated != undefined
&& (((time.epoch - voucher[code].activated) / 60) / 60) >= voucher[code].duration) {
console.log("vouchers - session expired - code: " + code + ", for MAC: "
+ voucher[code].mac + " removing IP: ", voucher[code].ip);
script.voucher.nft(voucher[code].ip, voucher[code].speed, "delete");
delete voucher[code];
file.write("voucher");
}
}
},
pruneGuest: function () {
let config = cfg.services.portal.guest;
let guestSpeed = cfg.network.speed.mac.findIndex(obj => obj.name === "guest")
// console.log("---------found guest speed in array position: " + guestSpeed)
for (const mac in guest) {
if (guest[mac] != undefined) {
if (config.hardLimit == true) {
if (guest[mac].lockout == true && ((time.epoch - guest[mac].update) / 60) >= config.lockoutPeriod) {
console.log("guest voucher - lockout period expired - for MAC: " + mac + " - removing lockout");
script.voucher.nft(guest[mac].ip, guestSpeed, "delete");
delete guest[mac];
file.write("guest");
}
if (((time.epoch - guest[mac].activated) / 69) >= config.duration) {
script.voucher.nft(guest[mac].ip, guestSpeed, "delete");
if (config.lockoutPeriod != undefined && config.lockoutPeriod > 0) {
console.log("guest voucher - session hard expired - for MAC: " + mac + ", removing IP: ",
guest[mac].ip + " - getting locked out for " + config.lockoutPeriod + " minutes");
guest[mac].lockout = true;
guest[mac].update = time.epoch;
} else {
console.log("guest voucher - session hard expired - mac: " + mac + ", removing IP: ", guest[mac].ip);
delete guest[mac];
}
file.write("guest");
}
} else if (((time.epoch - guest[mac].update) / 60) >= config.duration) {
console.log("guest voucher - session expired (no activity) - mac: " + mac + ", removing IP: ", guest[mac].ip);
script.voucher.nft(guest[mac].ip, guestSpeed, "delete");
delete guest[mac];
file.write("guest");
}
}
}
},
nft: function (ip, speed, action) {
let buf = ""
buf += " nft " + action + " element ip nat allow { " + ip + " }";
if (cfg.services.portal.enabled) {
if (cfg.network.gateway.mode == "teaming")
buf += "; nft " + action + " element ip mangle allow { " + ip + " }";
buf += "; nft " + action + " element ip filter " + cfg.network.speed.mac[speed].name + " { " + ip + " }";
}
cp.exec(buf, (e) => { if (e) console.error(e); });
},
},
}
app = {
nft: {
create: function (flush) {
nft = app.nft.command;
state.gatewaySelected = undefined;
console.log("nftables - creating basic filter rules");
cp.execSync('nft flush chain ip filter forward');
nft.update("filter forward", "icmp_allow", 'ip protocol icmp accept', true);
nft.update("filter forward", "conntrack_new_allow", 'ct state new ip daddr 0.0.0.0/0 accept', true);
if (cfg.network.restrict) {
if (cfg.network.restrict.dns && cfg.network.restrict.dns.length > 0) {
console.log("nftables - creating DNS block list - ", cfg.network.restrict.dns);
let list = cfg.network.interface[0].ip + ', ' + cfg.network.restrict.dns.join(",");
nft.update("filter forward", "dns_block", 'ip protocol { tcp, udp } th dport 53 drop', true);
nft.update("filter forward", "dns_allow", 'ip daddr { ' + list + ' } ip protocol { tcp, udp } th dport 53 accept', true);
}
}
nft.update("filter forward", "wireguard_allow_in", ' iifname "wg*" accept');
nft.update("filter forward", "wireguard_allow_out", ' oifname "wg*" accept');
if (flush !== false) {
arp = {};
console.log("nftables - flushing all speed limiter tables");
cfg.network.speed.mac.forEach(element => { nft.flush("filter", element.name); });
}
console.log("nftables - flushing mangle chain");
try { cp.execSync('nft flush chain ip mangle prerouting'); }
catch {
try { nft.cTable("mangle", "prerouting", "filter", "dstnat", "accept"); }
catch {
cp.execSync('nft flush table ip mangle');
nft.cTable("mangle", "prerouting", "filter", "dstnat", "accept");
}
}
state.nfTables.mangle = undefined;
if (cfg.network.speed.mac[1] != undefined || cfg.network.speed.ip.length > 0) {
nft.delete("filter forward", "speed_unrestricted");
cp.execSync('nft add chain ip filter speed_limiter');
cp.execSync('nft flush chain ip filter speed_limiter');
nft.add("filter forward", "speed_jump", "jump speed_limiter");
cp.execSync('nft add rule ip filter speed_limiter ct state new ip daddr 0.0.0.0/0 accept');
} else {
console.log("nftables - speed - setting no limiters");
nft.delete("filter forward", "speed_jump");
nft.add("filter forward", "speed_unrestricted", "ct state related,established ip daddr 0.0.0.0/0 accept");
}
if (cfg.network.speed.ip.length > 0) {
console.log("nftables - speed - creating MAC limiters");
nft.speedIP();
}
if (cfg.network.speed.mac[1] != undefined) {
console.log("nftables - speed - creating MAC limiters");
nft.speedMAC();
}
if (cfg.services.portal.enabled) {
console.log("nftables - setting up nat for portal");
if (flush !== false) {
nft.flush("nat", "allow");
nft.flush("mangle", "allow");
try { cp.execSync('nft flush chain ip nat prerouting'); }
catch { createNat(); }
cp.execSync('nft flush chain ip nat postrouting');
}
nft.update("nat prerouting", "nat_portal_redirect_dns", 'ip saddr != @allow udp dport 53 dnat to '
+ cfg.network.interface[0].ip + ':52');
// nft.update("nat prerouting", "nat_portal_redirect_http", 'ip saddr != @allow tcp dport 80 dnat to '
// + cfg.network.interface[0].ip + ':80');
// nft.update("nat prerouting", "nat_portal_redirect_https", 'ip saddr != @allow tcp dport 443 dnat to '
// + cfg.network.interface[0].ip + ':443');
nft.update('nat postrouting', 'masquerade', 'ip saddr @allow oif "'
+ ((cfg.network.interface[1]) ? cfg.network.interface[1].if : cfg.network.interface[0].if) + '" masquerade');
} else {
console.log("nftables - creating outbound nat");
try { cp.execSync('nft flush chain ip nat prerouting'); } catch { createNat(); }
nft.update("nat postrouting", "masquerade", 'ip saddr ' + cfg.network.interface[0].subnetCIDR[0] + '/'
+ cfg.network.interface[0].subnetCIDR[1] + ' oif "' + ((cfg.network.interface[1])
? cfg.network.interface[1].if : cfg.network.interface[0].if) + '" masquerade');
}
function createNat() {
cp.execSync('nft add table ip nat');
cp.execSync('nft add chain ip nat prerouting "{ type nat hook prerouting priority filter; policy accept; }"');
cp.execSync('nft add chain ip nat postrouting "{ type nat hook postrouting priority srcnat; policy accept; }"');
}
if (cfg.network.gateway.startAll) script.mangle();
},
tables: {
mangle: [
{
rule: {
family: "ip",
table: "mangle",
chain: "prerouting",
expr: [
{
match: {
op: "==",
left: {
payload: {
protocol: "ip",
field: "daddr"
}
},
right: {
set: [
{
prefix: {
addr: "10.0.0.0",
len: 8
}
},
{
prefix: {
addr: "192.168.0.0",
len: 16
}
},
{
prefix: {
addr: "172.16.0.0",
len: 16
}
}
]
}
}
},
{
return: null
}
]
}
},
{
rule: {
family: "ip",
table: "mangle",
chain: "prerouting",
expr: [
{
match: {
op: "==",
left: {
payload: {
protocol: "ip",
field: "saddr"
}
},
right: "127.0.0.1"
}
},
{
return: null
}
]
}
},
{
rule: {
family: "ip",
table: "mangle",
chain: "prerouting",
comment: "nfsense_mangle",
expr: [
{
match: {
op: "==",
left: {
payload: {
protocol: "ip",
field: "daddr"
}
},
right: {
prefix: {
addr: "0.0.0.0",
len: 0
}
}
}
},
{
match: {
op: "in",
left: {
ct: {
key: "state"
}
},
right: "new"
}
},
{
mangle: {
key: {
ct: {
key: "mark"
}
},
value: {
map: {
key: {
numgen: {
mode: "inc",
mod: 1,
offset: 0
}
},
data: {
set: [[0, 1]]
}
}
}
}
}
]
}
},
{
rule: {
family: "ip",
table: "mangle",
chain: "prerouting",
expr: [
{
match: {
op: "==",
left: {
payload: {
protocol: "ip",
field: "daddr"
}
},
right: {
prefix: {
addr: "0.0.0.0",
len: 0
}
}
}
},
{
match: {
op: "in",
left: {
ct: {
key: "state"
}
},
right: [
"established",
"related"
]
}
},
{
mangle: {
key: {
ct: {
key: "mark"
}
},
value: {
ct: {
key: "mark"
}
}
}
}
]
}
},
{
rule: {
family: "ip",
table: "mangle",
chain: "prerouting",
expr: [
{
mangle: {
key: {
meta: {
key: "mark"
}
},
value: {
ct: {
key: "mark"
}
}
}
}
]
}
}
]
},
command: {
cTable: function (table, chain, type, priority, policy) {
console.log("nftables - creating table - " + table);
cp.execSync('nft add table ip ' + table);
console.log("nftables - creating chain - " + table + " " + chain);
cp.execSync('nft add chain ip ' + table + ' ' + chain + ' "{ type ' + type + ' hook '
+ chain + ' priority ' + priority + '; policy ' + policy + '; }"');
},
flush: function (chain, name) {
try {
console.log("nftables - flushing set - " + chain + " - " + name);
cp.execSync('nft flush set ip ' + chain + ' ' + name);
}
catch {
console.log("nftables - set not found, creating - " + chain + " - " + name);
cp.execSync('nft add set ip ' + chain + ' ' + name + ' "{ type ipv4_addr; }"');
}
},
delete: function (chain, name) {
let handleNum = Number(parse(cp.execSync('nft -a list chain ip ' + chain).toString()
, '"nfsense_' + name + '" # handle ', '\n'));
if (isNaN(handleNum)) {
console.log("nftables - cannot delete rule - " + chain + " - " + name + ' - rule not found');
} else {
console.log("nftables - deleting rule - " + chain + " - " + name);
cp.execSync('nft delete rule ip ' + chain + ' handle ' + handleNum);
}
},
update: function (chain, name, rule, insert) {
let handleNum = Number(parse(cp.execSync('nft -a list chain ip ' + chain).toString()
, '"nfsense_' + name + '" # handle ', '\n'));
if (isNaN(handleNum)) {
console.log("nftables - creating rule - " + chain + " - " + name);
cp.execSync('nft ' + (insert ? 'insert' : 'add') + ' rule ip ' + chain + ' ' + rule + ' comment "nfsense_' + name + '"')
} else {
console.log('nftables - updating rule - ' + chain + ' - ' + name);
cp.execSync('nft replace rule ip ' + chain + ' handle ' + handleNum + ' ' + rule + ' comment "nfsense_' + name + '"');
}
},
add: function (chain, name, rule) {
let handleNum = Number(parse(cp.execSync('nft -a list chain ip ' + chain).toString()
, '"nfsense_' + name + '" # handle ', '\n'));
if (isNaN(handleNum)) {
console.log("nftables - creating rule - " + chain + " - " + name);
cp.execSync('nft add rule ip ' + chain + ' ' + rule + ' comment "nfsense_' + name + '"');
} else console.log("nftables - creating rule aborted, exists already - " + chain + " - " + name);
},
getHandle: function (chain, name) {
let handleNum = parse(cp.execSync('nft -a list chain ip ' + chain).toString()
, '"nfsense_' + name + '" # handle ', '\n');
return Number(handleNum);
},
speedMAC: function () {
timeout = 0;
let buf = [ // unrestricted class rules
{
add:
{
rule: {
family: "ip",
table: "filter",
chain: "speed_limiter",
handle: 20,
expr: [
{
match: {
op: "in",
left: {
ct: {
key: "state"
}
},
right: [
"established",
"related"
]
}
},
{
match: {
op: "==",
left: {
payload: {
protocol: "ip",
field: "saddr"
}
},
right: {
prefix: {
addr: "0.0.0.0",
len: 0
}
}
}
},
{
match: {
op: "==",
left: {
payload: {
protocol: "ip",
field: "daddr"
}
},
right: "@unrestricted"
}
},
{
accept: null
}
]
}
}
},
{
add: {
rule: {
family: "ip",
table: "filter",
chain: "speed_limiter",
expr: [
{
match: {
op: "in",
left: {
ct: {
key: "state"
}
},
right: [
"established",
"related"
]
}
},
{
match: {
op: "==",
left: {
payload: {
protocol: "ip",
field: "saddr"
}
},
right: "@unrestricted"
}
},
{
match: {
op: "==",
left: {
payload: {
protocol: "ip",
field: "daddr"
}
},
right: {
prefix: {
addr: "0.0.0.0",