Project

General

Profile

Bug #12838 » server.rb

 
#!/usr/bin/env ruby

require "socket"
require "pry"
require "pry-byebug"

Socket.udp_server_loop(53) do |msg, msg_src|
id, flags, qdcount, ancount, nscount, arcount = msg.unpack("nnnnnn")

qr = (flags & 0x8000) >> 15
opcode = (flags & 0x7800) >> 11
aa = (flags & 0x0400) >> 10
tc = (flags & 0x0200) >> 9
rd = (flags & 0x0100) >> 8
ra = (flags & 0x0080) >> 7
z = (flags & 0x0070) >> 4
rcode = flags & 0x000f
rest = msg[12..-1]

questions = msg.bytes[12..-1]
labels = []
idx = 0
while idx < questions.length-5
size = questions[idx]
labels << questions[idx+1..idx+size].pack('c*')
idx += size+1
end
hostname = labels.join('.')

puts "Received Query for : #{hostname}"

if hostname == "example.good.com"
id = id
qr = 1
opcode = opcode
aa = 0
tc = 0
rd = rd
ra = 1
z = 0
rcode = 0
qdcount = 1
ancount = 1
nscount = 0
arcount = 0
word2 = (qr << 15) |
(opcode << 11) |
(aa << 10) |
(tc << 9) |
(rd << 8) |
(ra << 7) |
(z << 4) |
rcode
msg = [id, word2, qdcount, ancount, nscount, arcount].pack("nnnnnn")
msg << questions.pack('c*')
type = 1
klass = 1
ttl = 3600
rdlength = 4
rdata = [52,0,2,1].pack("CCCC")
rr = [0xc00c, type, klass, ttl, rdlength, rdata].pack("nnnNna*")
msg << rr
rdata = [52,0,2,2].pack("CCCC")
rr = [0xc00c, type, klass, ttl, rdlength, rdata].pack("nnnNna*")
msg << rr

puts "Returning single response with records"
msg_src.reply msg
else
id = id
qr = 1
opcode = opcode
aa = 0
tc = 0
rd = rd
ra = 1
z = 0
rcode = 3
qdcount = 1
ancount = 0
nscount = 0
arcount = 0
word2 = (qr << 15) |
(opcode << 11) |
(aa << 10) |
(tc << 9) |
(rd << 8) |
(ra << 7) |
(z << 4) |
rcode
msg = [id, word2, qdcount, ancount, nscount, arcount].pack("nnnnnn")
msg << questions.pack('c*')

puts "Returning duplicate responses with \"Not found\" RCODE"
msg_src.reply msg
msg_src.reply msg
end
end
(1-1/3)