Advertisement
Guest User

DNS A record filter proxy v2

a guest
Aug 25th, 2017
848
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. let dns = require('native-dns');
  4. let server = dns.createUDPServer({ dgram_type: 'udp6' });
  5.  
  6. function secureExit() {
  7.     try {
  8.         server.close();
  9.     } catch (err) {}
  10.     process.exit(1);
  11. }
  12.  
  13. function exitWithError(err) {
  14.     console.error(err);
  15.     secureExit();
  16. }
  17.  
  18. process.once('SIGINT', () => exitWithError('Received SIGINT'));
  19. process.once('SIGTERM', () => exitWithError('Received SIGTERM'));
  20.  
  21. function beReady(){
  22.     console.log('server listening on', server.address());
  23.     try {
  24.         process.setgid('nogroup');
  25.         process.setuid('nobody');
  26.     } catch (err) {
  27.         exitWithError('can\'t drop privileges');
  28.     }
  29. }
  30.  
  31. server.on('listening', beReady);
  32. server.on('close', () => console.log('server closed', server.address()));
  33. server.on('error', (err, buff, req, res) => exitWithError(err.stack));
  34. server.on('socketError', (err, socket) => exitWithError(err));
  35.  
  36. server.serve(53, 'localhost');
  37.  
  38. let authority = { address: '2001:4860:4860::8888', port: 53, type: 'udp' };
  39.  
  40. function proxy(question, response, cb) {
  41.     var request = dns.Request({
  42.         question: question, // forwarding the question
  43.         server: authority,  // this is the DNS server we are asking
  44.         timeout: 1000
  45.     });
  46.  
  47.     // when we get answers, append them to the response
  48.     request.on('message', (err, msg) => {
  49.         msg.answer.forEach(a => {
  50.             if (a.type != 1) {
  51.                 response.answer.push(a);
  52.             }
  53.         });
  54.     });
  55.  
  56.     request.on('end', cb);
  57.     request.send();
  58. }
  59.  
  60. let async = require('async');
  61.  
  62. function handleRequest(request, response) {
  63.     let f = []; // array of functions
  64.  
  65.     // proxy all questions
  66.     // since proxying is asynchronous, store all callbacks
  67.     request.question.forEach(question => {
  68.         f.push(cb => proxy(question, response, cb));
  69.     });
  70.  
  71.     // do the proxying in parallel
  72.     // when done, respond to the request by sending the response
  73.     async.parallel(f, function() { response.send(); });
  74. }
  75.  
  76. server.on('request', handleRequest);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement