Skip to content

Instantly share code, notes, and snippets.

@honnix
Created January 23, 2013 12:52
Show Gist options
  • Save honnix/4605201 to your computer and use it in GitHub Desktop.
Save honnix/4605201 to your computer and use it in GitHub Desktop.
play dns with ruby
#!/usr/bin/env ruby
# Copyright (c) 2009 Samuel Williams. Released under the GNU GPLv3.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
require 'rexec'
require 'rexec/daemon'
require 'rubydns'
# Run as user "daemon"
RUN_AS = "daemon"
# We need to be root in order to bind to privileged port
if RExec.current_user != "root"
$stderr.puts "Sorry, this command needs to be run as root!"
exit 1
end
# Helper
Name = Resolv::DNS::Name
IN = Resolv::DNS::Resource::IN
LAB = "xxx.xxx.xxx.xxx"
NET = "yyy.yyy.yyy.yyy"
# The Daemon itself
class DNSServer < RExec::Daemon::Base
@@var_directory = '/var/'
def self.run
# Don't buffer output (for debug purposes)
$stderr.sync = true
# Use upstream DNS for name resolution
$LAB = Resolv::DNS.new(:nameserver => LAB)
$NET = Resolv::DNS.new(:nameserver => NET)
# Start the RubyDNS server
RubyDNS::run_server do
on(:start) do
RExec.change_user(RUN_AS)
logger.level = Logger::INFO
end
match(/sip\.xxx\.com$/, IN::A) do |match, transaction|
logger.info "#{match} go through lab"
transaction.passthrough!($LAB)
end
match(/^*\.xxx\.net$/, IN::A) do |match, transaction|
logger.info "#{match} go through lab"
transaction.passthrough!($LAB)
end
match(/^*\.xxx\..*$/, IN::A) do |match, transaction|
logger.info "#{match} go through net"
transaction.passthrough!($NET)
end
# Default DNS handler
otherwise do |transaction|
logger.info 'go through default'
transaction.passthrough!($LAB)
end
end
end
end
# RExec daemon runner
DNSServer.daemonize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment