-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
227 lines (201 loc) · 6.24 KB
/
Copy pathmain.js
File metadata and controls
227 lines (201 loc) · 6.24 KB
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
function ipToInt(ip) {
const parts = ip.trim().split('.');
if (parts.length !== 4) throw new Error('Invalid IP');
return parts.reduce((acc, octet) => {
const n = parseInt(octet, 10);
if (isNaN(n) || n < 0 || n > 255) throw new Error('Invalid IP');
return acc * 256 + n;
}, 0) >>> 0;
}
function intToIp(int) {
int = int >>> 0;
return [
Math.floor(int / Math.pow(256, 3)) % 256,
Math.floor(int / Math.pow(256, 2)) % 256,
Math.floor(int / 256) % 256,
int % 256,
].join('.');
}
function cidrToRange(cidr) {
const parts = cidr.trim().split('/');
if (parts.length !== 2) throw new Error('Invalid CIDR');
const [ip, maskStr] = parts;
const m = parseInt(maskStr, 10);
if (isNaN(m) || m < 0 || m > 32) throw new Error('Invalid mask');
const ipInt = ipToInt(ip.trim());
const blockSize = m === 0 ? Math.pow(2, 32) : Math.pow(2, 32 - m);
if (m > 0 && (ipInt % blockSize) !== 0) {
throw new Error('Host bits set');
}
const start = Math.floor(ipInt / blockSize) * blockSize;
const end = (start + blockSize - 1) >>> 0;
return [start >>> 0, end >>> 0];
}
function* rangeToCidrsGen(start, end) {
let current = Number(start);
const MAX32 = Math.pow(2, 32);
while (current <= end) {
let alignPow = 1;
if (current === 0) {
alignPow = MAX32;
} else {
while (alignPow * 2 <= MAX32 && current % (alignPow * 2) === 0) {
alignPow *= 2;
}
}
const prefAlign = 32 - Math.floor(Math.log2(alignPow));
const remaining = end - current + 1;
const prefRange = 32 - Math.floor(Math.log2(remaining));
let prefix = Math.max(prefAlign, prefRange);
if (prefix < 0) prefix = 0;
if (prefix > 32) prefix = 32;
const blockSize = Math.pow(2, 32 - prefix);
yield `${intToIp(current >>> 0)}/${prefix}`;
if (blockSize <= 0 || !isFinite(blockSize)) break;
current = current + blockSize;
}
}
function mySorted(netArray) {
for (let i = 0; i < netArray.length - 1; i++) {
for (let j = 0; j < netArray.length - i - 1; j++) {
const a = netArray[j].split('/')[0];
const b = netArray[j + 1].split('/')[0];
const aInt = ipToInt(a);
const bInt = ipToInt(b);
if (aInt > bInt) {
[netArray[j], netArray[j + 1]] = [netArray[j + 1], netArray[j]];
}
}
}
return netArray;
}
function rangeSubstraction(allowedRange, disallowedRange) {
let result = [...allowedRange];
for (const disallowed of disallowedRange) {
const newResult = [];
for (const allowed of result) {
if (allowed[1] < disallowed[0] || allowed[0] > disallowed[1]) {
newResult.push(allowed);
} else {
if (allowed[0] < disallowed[0]) {
newResult.push([allowed[0], disallowed[0] - 1]);
}
if (allowed[1] > disallowed[1]) {
newResult.push([disallowed[1] + 1, allowed[1]]);
}
}
}
result = newResult;
}
return result;
}
function summarizeNets(IPArr) {
if (IPArr.length === 0) return [];
IPArr.sort((a, b) => a[0] - b[0]);
const result = [IPArr[0]];
for (let i = 1; i < IPArr.length; i++) {
const last = result[result.length - 1];
if (last[1] + 1 >= IPArr[i][0]) {
last[1] = Math.max(last[1], IPArr[i][1]);
} else {
result.push(IPArr[i]);
}
}
return result;
}
function mainCalculator(allowedNet, disallowedNet) {
const allowedNetTextArr = allowedNet.split(',');
const disallowedNetTextArr = disallowedNet.split(',');
const allowedNetTextArrSorted = mySorted(allowedNetTextArr);
const disallowedNetTextArrSorted = mySorted(disallowedNetTextArr);
const allowedNetArr = [];
const disallowedNetArr = [];
for (const x of allowedNetTextArrSorted) {
try {
allowedNetArr.push(cidrToRange(x));
} catch (e) {
console.log(`Error: ${x} has host bits set or incorrect format`);
return;
}
}
for (const x of disallowedNetTextArrSorted) {
try {
disallowedNetArr.push(cidrToRange(x));
} catch (e) {
console.log(`Error: ${x} has host bits set or incorrect format`);
return;
}
}
const allowedNetRanges = summarizeNets(allowedNetArr);
const disallowedNetRanges = summarizeNets(disallowedNetArr);
const resultRanges = rangeSubstraction(allowedNetRanges, disallowedNetRanges);
if (resultRanges.length == 0) {
console.log('There are no allowed networks!');
return;
}
const MAXIP = Math.pow(2, 32) - 1;
const cleaned = [];
for (const r of resultRanges) {
const s = Math.max(0, r[0]);
const e = Math.min(MAXIP, r[1]);
if (s <= e) cleaned.push([s, e]);
}
if (cleaned.length === 0) {
console.log('There are no allowed networks!');
return;
}
resultRanges.length = 0;
for (const r of cleaned) resultRanges.push(r);
resultRanges.sort((a, b) => a[0] - b[0]);
let wroteAny = false;
process.stdout.write('AllowedIPs = ');
for (const range of resultRanges) {
for (const cidr of rangeToCidrsGen(range[0], range[1])) {
if (wroteAny) process.stdout.write(',');
process.stdout.write(cidr);
wroteAny = true;
}
}
if (!wroteAny) {
console.log('There are no allowed networks!');
} else {
process.stdout.write('\n');
}
return;
}
function main() {
const args = process.argv.slice(2);
if (args.length === 0 || args.includes('-h')) {
const help = `
WireGuard allowedNets Calculator
Keys:
-a <network/mask[,network2/mask][,network3/mask],...>: Allowed networks. Leave blank for 0.0.0.0/0
-d <network/mask[,network2/mask][,network3/mask],...>: Disallowed networks. Optional if "-e" is used
-e: Preset for fast excluding local networks
-h: print help message to console
`;
console.log(help);
return;
}
let allowedNet = '';
let disallowedNet = '';
const aIndex = args.indexOf('-a');
if (aIndex !== -1 && aIndex + 1 < args.length) {
allowedNet = args[aIndex + 1];
} else {
allowedNet = '0.0.0.0/0';
}
const dIndex = args.indexOf('-d');
if (dIndex !== -1 && dIndex + 1 < args.length) {
disallowedNet = args[dIndex + 1];
} else if (args.includes('-e')) {
disallowedNet = '10.0.0.0/8,127.0.0.0/8,169.254.0.0/16,172.16.0.0/12,192.168.0.0/16';
} else {
console.log('Either disallowed networks or -e preset is needed');
return;
}
mainCalculator(allowedNet, disallowedNet);
}
if (require.main === module) {
main();
}