This repository has been archived by the owner on Jan 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
526 lines (446 loc) · 14.3 KB
/
index.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
const dgram = require('dgram');
const server = dgram.createSocket('udp6');
const serverTCP = require('net').createServer();
const dnsPacket = require('dns-packet');
const { EventEmitter } = require('events');
const fs = require('fs');
const path = require('path');
const cron = require('node-cron');
// https://support.umbrella.com/hc/en-us/articles/232254248-Common-DNS-return-codes-for-any-DNS-service-and-Umbrella-
let NOERROR_RCODE = 0x00;
let SERVFAIL_RCODE = 0x02;
let NXDOMAIN_RCODE = 0x03;
let NOTIMP_RCODE = 0x04;
let CACHE_MINUTES = 5;
var cache = {};
var beingCached = {};
var toSaveCache = {};
if (fs.existsSync(path.join(__dirname, 'cache.json'))) {
console.log('Cache file exists, loading data from cache file');
cache = JSON.parse(fs.readFileSync(path.join(__dirname, 'cache.json')));
}
function saveCacheToFile() {
console.log('Saving to cache file');
fs.writeFileSync(path.join(__dirname, 'cache.json'), JSON.stringify(cache));
}
cron.schedule('*/5 * * * *', () => {
saveCacheToFile();
});
function saveCache() {
toSaveCache = Object.assign({}, cache);
}
var event = new EventEmitter();
server.on('error', (err) => {
console.log(`server error:\n${err.stack}`);
server.close();
process.exit(1);
});
serverTCP.on('error', (err) => {
console.log(`server error:\n${err.stack}`);
serverTCP.close();
process.exit(1);
});
serverTCP.on('connection', (socket) => {
console.log(`TCP connection from ${socket.remoteAddress}:${socket.remotePort}`);
socket.on('data', function(data) {
//console.log(data.toString());
event.emit('query', 'tcp', data, {
address: socket.remoteAddress,
port: socket.remotePort,
socket
});
});
});
server.on('message', (msg, rinfo) => {
console.log(`UDP connection from ${rinfo.address}:${rinfo.port}`);
event.emit('query', 'udp', msg, rinfo);
});
function dnsQuery(name, type, packet, cb) {
const socket = dgram.createSocket('udp4');
let _timeout = 2000;
let _socketClosed = false;
const buf = dnsPacket.encode({
type: 'query',
id: packet ? packet.id : null,
flags: dnsPacket.RECURSION_DESIRED,
questions: [{
type,
name
}]
});
socket.on('message', message => {
socket.close();
_socketClosed = true;
cb(null, dnsPacket.decode(message));
});
socket.on('error', error => {
socket.close();
_socketClosed = true;
cb(error, null);
});
socket.send(buf, 0, buf.length, 53, '8.8.8.8');
setTimeout(function() {
if (!_socketClosed) {
socket.close();
}
}, _timeout);
}
function queryNotA(query, packet, type, sender) {
var thisCache = {};
if (cache[query.name]) {
thisCache = cache[query.name];
}
thisCache[query.type] = {};
var error = false;
dnsQuery(query.name, query.type, packet, function(err, data) {
if (err) {
if (err.code !== 'ENODATA' && err.code !== 'ENOTFOUND') {
error = true;
console.error(err);
}
}
var answerData = {
type: 'response',
id: packet ? packet.id : null,
flags: dnsPacket.RECURSION_DESIRED | dnsPacket.RECURSION_AVAILABLE,
questions: [query],
answers: []
};
//console.log(`qid: ${packet.id}`);
if (error) {
answerData.flags = SERVFAIL_RCODE;
} else if (data) {
answerData = data;
answerData.id = packet ? packet.id : null;
thisCache[query.type].data = answerData;
if (answerData.answers[0]) {
thisCache[query.type].expiresAt = Date.now() + (answerData.answers[0].ttl * 1000);
} else {
thisCache[query.type].expiresAt = Date.now() + (CACHE_MINUTES * 60 * 1000);
}
cache[query.name] = thisCache;
saveCache();
if (beingCached[query.name]) {
beingCached[query.name] = beingCached[query.name].filter(e => e !== query.type);
}
}
if (sender) {
if (type === 'udp') {
server.send(dnsPacket.encode(answerData), sender.port, sender.address, function(err, bytes) {
if (err) {
return console.error(err);
}
//console.log(bytes);
console.log(`Answered UDP request: ${query.type} ${query.name} for ${sender.address}`);
});
} else {
sender.socket.write(dnsPacket.streamEncode(answerData), function() {
console.log(`Answered TCP request: ${query.type} ${query.name} for ${sender.address}`);
sender.socket.end();
});
}
}
});
}
function queryAorAAAA(query, packet, type, sender) {
dnsQuery(query.name, 'A', packet, function(err4, data4) {
var v4Answer = false;
var v4Error = false;
var v4FailError = false;
if (err4) {
v4Error = true;
if (err4.code !== 'ENODATA' && err4.code !== 'ENOTFOUND') {
console.log(`Error doing DNS lookup: ${err4}`);
v4FailError = true;
var answerDataError = {
type: 'response',
id: packet ? packet.id : null,
flags: SERVFAIL_RCODE,
questions: [query],
answers: []
};
if (sender) {
if (type === 'udp') {
server.send(dnsPacket.encode(answerDataError), sender.port, sender.address, function(err, bytes) {
if (err) {
return console.error(err);
}
//console.log(bytes);
});
} else {
sender.socket.write(dnsPacket.streamEncode(answerDataError), function() {
sender.socket.end();
});
}
}
return console.error(err4);
}
}
//console.log(data4);
dnsQuery(query.name, 'AAAA', packet, function(err6, data6) {
var thisCache = {};
if (cache[query.name]) {
thisCache = cache[query.name];
}
thisCache[query.type] = {};
var v6Answer = false;
var v6Error = false;
var v6FailError = false;
if (err6) {
v6Error = true;
if (err6.code !== 'ENODATA' && err6.code !== 'ENOTFOUND') {
console.log(`Error doing DNS lookup: ${err6}`);
v6FailError = true;
var answerDataError = {
type: 'response',
id: packet ? packet.id : null,
flags: SERVFAIL_RCODE,
questions: [query],
answers: []
};
if (sender) {
if (type === 'udp') {
server.send(dnsPacket.encode(answerDataError), sender.port, sender.address, function(err, bytes) {
if (err) {
return console.error(err);
}
//console.log(bytes);
});
} else {
sender.socket.write(dnsPacket.streamEncode(answerDataError), function() {
sender.socket.end();
});
}
}
return console.error(err6);
}
}
//console.log(data6);
if (!v4Error && data4.answers.length !== 0) {
if (data4.answers.length === 1 && data4.answers[0].type === 'CNAME') {
v4Answer = false;
} else {
v4Answer = true;
}
}
if (!v6Error && data6.answers.length !== 0) {
if (data6.answers.length === 1 && data6.answers[0].type === 'CNAME') {
v6Answer = false;
} else {
v6Answer = true;
}
}
//console.log(`4: ${v4Answer}`);
//console.log(`6: ${v6Answer}`);
//console.log(`b: ${v4Answer && v6Answer}`);
var data4Data = data4;
data4Data.id = packet ? packet.id : null;
var data6Data = data6;
data6Data.id = packet ? packet.id : null;
var answerVersionData = v4Answer ? data4.answer : data6.answer;
var answerType = v4Answer ? 'A' : 'AAAA';
if (!v4Answer && !v6Answer) {
var answerData = query.type === 'A' ? data4Data : data6Data;
if (answerData.authorities.length > 0) {
thisCache[query.type].data = answerData;
thisCache[query.type].expiresAt = Date.now() + (answerData.authorities[0].data.minimum * 1000);
cache[query.name] = thisCache;
saveCache();
if (beingCached[query.name]) {
beingCached[query.name] = beingCached[query.name].filter(e => e !== query.type);
}
}
if (sender) {
if (type === 'udp') {
server.send(dnsPacket.encode(answerData), sender.port, sender.address, function(err, bytes) {
if (err) {
return console.error(err);
}
//console.log(bytes);
});
} else {
sender.socket.write(dnsPacket.streamEncode(answerData), function() {
sender.socket.end();
});
}
}
} else if ((answerType === 'AAAA' && query.type === 'A') || (answerType === 'A' && query.type === 'AAAA')) {
// eslint-disable-next-line no-redeclare
var answerData = answerType === 'A' ? data4Data : data6Data;
answerData.questions[0].type = query.type;
var _ttl = answerData.answers[0] ? answerData.answers[0].ttl : 0;
if (answerData.answers[0].type !== 'CNAME') {
answerData.answers = [];
} else {
answerData.answers = answerData.answers.slice(0, 1);
}
//console.log(answerData);
thisCache[query.type].data = answerData;
thisCache[query.type].expiresAt = Date.now() + (_ttl * 1000);
cache[query.name] = thisCache;
saveCache();
if (beingCached[query.name]) {
beingCached[query.name] = beingCached[query.name].filter(e => e !== query.type);
}
if (sender) {
if (type === 'udp') {
server.send(dnsPacket.encode(answerData), sender.port, sender.address, function(err, bytes) {
if (err) {
return console.error(err);
}
//console.log(bytes);
});
} else {
sender.socket.write(dnsPacket.streamEncode(answerData), function() {
sender.socket.end();
});
}
}
} else {
// eslint-disable-next-line no-redeclare
var answerData = query.type === 'A' ? data4Data : data6Data;
thisCache[query.type].data = answerData;
if (answerData.answers[0]) {
thisCache[query.type].expiresAt = Date.now() + (answerData.answers[0].ttl * 1000);
} else {
thisCache[query.type].expiresAt = Date.now() + (CACHE_MINUTES * 60 * 1000);
}
var cachedOtherRecord = query.type === 'A' ? data6Data : data4Data;
if (answerData.answers[0].type !== 'CNAME') {
cachedOtherRecord.answers = [];
} else {
cachedOtherRecord.answers = answerData.answers.slice(0, 1);
}
thisCache[query.type === 'A' ? 'AAAA' : 'A'] = {};
thisCache[query.type === 'A' ? 'AAAA' : 'A'].data = cachedOtherRecord;
if (answerData.answers[0]) {
thisCache[query.type === 'A' ? 'AAAA' : 'A'].expiresAt = Date.now() + (answerData.answers[0].ttl * 1000);
} else {
thisCache[query.type === 'A' ? 'AAAA' : 'A'].expiresAt = Date.now() + (CACHE_MINUTES * 60 * 1000);
}
cache[query.name] = thisCache;
saveCache();
if (beingCached[query.name]) {
beingCached[query.name] = beingCached[query.name].filter(e => e !== query.type);
}
if (sender) {
if (type === 'udp') {
server.send(dnsPacket.encode(answerData), sender.port, sender.address, function(err, bytes) {
if (err) {
return console.error(err);
}
//console.log(bytes);
console.log(`Answered UDP request: ${query.type} ${query.name} for ${sender.address}`);
});
} else {
sender.socket.write(dnsPacket.streamEncode(answerData), function() {
console.log(`Answered TCP request: ${query.type} ${query.name} for ${sender.address}`);
sender.socket.end();
});
}
}
}
});
});
}
event.on('query', function(type, msg, rinfo) {
//console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
let packet;
if (type === 'udp') {
packet = dnsPacket.decode(msg);
} else {
packet = dnsPacket.streamDecode(msg);
}
//console.log(packet);
let query;
var _throwError = SERVFAIL_RCODE;
try {
query = packet.questions[0];
//var supportedTypes = ['A', 'AAAA', 'CNAME', 'MX', 'NS', 'PTR', 'SRV', 'TXT'];
var supportedTypes = ['A', 'AAAA', 'CAA', 'CNAME', 'DNAME', 'DNSKEY', 'DS', 'HINFO', 'MX', 'NS', 'NSEC', 'NSEC3', 'NULL', 'PTR', 'SOA', 'SRV', 'TXT'];
if (!supportedTypes.includes(query.type)) {
_throwError = NOTIMP_RCODE;
throw new Error();
}
} catch (e) {
var answerDataError = {
type: 'response',
id: packet ? packet.id : null,
flags: _throwError,
questions: [query],
answers: []
};
if (type === 'udp') {
server.send(dnsPacket.encode(answerDataError), rinfo.port, rinfo.address, function(err, bytes) {
if (err) {
return console.error(err);
}
//console.log(bytes);
console.log(`Received invalid UDP request from ${rinfo.address}. ${_throwError === NOTIMP_RCODE ? 'Type not implemented' : 'General error'}`);
});
} else {
rinfo.socket.write(dnsPacket.streamEncode(answerDataError), function() {
console.log(`Received invalid TCP request from ${rinfo.address}. ${_throwError === NOTIMP_RCODE ? 'Type not implemented' : 'General error'}`);
rinfo.socket.end();
});
}
return;
}
//console.log(query.type);
if (cache[query.name] && cache[query.name][query.type] && cache[query.name][query.type].data) {
var _answerData = Object.assign({}, cache[query.name][query.type].data);
_answerData.id = packet ? packet.id : null;
var dataAnswers = _answerData.answers;
var expiresAt = cache[query.name][query.type].expiresAt;
for (var i = 0; i < dataAnswers.length; i++) {
var ttlLeft = Math.floor((expiresAt - Date.now()) / 1000);
if (ttlLeft < 0) {
ttlLeft = 0;
}
dataAnswers[i].ttl = ttlLeft;
}
if (type === 'udp') {
server.send(dnsPacket.encode(_answerData), rinfo.port, rinfo.address, function(err, bytes) {
if (err) {
return console.error(err);
}
//console.log(bytes);
console.log(`Answered UDP request: ${query.type} ${query.name} for ${rinfo.address} from cache`);
});
} else {
rinfo.socket.end(dnsPacket.streamEncode(_answerData), function() {
console.log(`Answered TCP request: ${query.type} ${query.name} for ${rinfo.address} from cache`);
});
}
if (cache[query.name] && cache[query.name][query.type] && cache[query.name][query.type].expiresAt < Date.now()) {
if (!(beingCached[query.name] && beingCached[query.name].includes(query.type))) {
console.log(`Cache for ${query.type} ${query.name} expired. Requesting new data to cache`);
//delete cache[query.name][query.type];
if (!beingCached[query.name]) {
beingCached[query.name] = [];
}
beingCached[query.name].push(query.type);
if (!['A', 'AAAA'].includes(query.type)) {
queryNotA(query, null, null, null);
} else {
queryAorAAAA(query, null, null, null);
}
}
}
//console.log(cache[query.name][query.type]);
} else if (!['A', 'AAAA'].includes(query.type)) {
queryNotA(query, packet, type, rinfo);
} else {
queryAorAAAA(query, packet, type, rinfo);
}
});
server.on('listening', () => {
const address = server.address();
console.log(`UDP server listening ${address.address}:${address.port}`);
});
server.bind(41234, '::');
serverTCP.on('listening', () => {
const address = server.address();
console.log(`TCP server listening ${address.address}:${address.port}`);
});
serverTCP.listen(41234, '::');