Project

General

Profile

Bug #12838 ยป server.rb

 
1
#!/usr/bin/env ruby
2

    
3
require "socket"
4
require "pry"
5
require "pry-byebug"
6

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

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

    
20
  questions = msg.bytes[12..-1]
21
  labels = []
22
  idx = 0
23
  while idx < questions.length-5
24
    size = questions[idx]
25
    labels << questions[idx+1..idx+size].pack('c*')
26
    idx += size+1
27
  end
28
  hostname = labels.join('.')
29

    
30
  puts "Received Query for : #{hostname}"
31

    
32
  if hostname == "example.good.com"
33
    id = id
34
    qr = 1
35
    opcode = opcode
36
    aa = 0
37
    tc = 0
38
    rd = rd
39
    ra = 1
40
    z = 0
41
    rcode = 0
42
    qdcount = 1
43
    ancount = 1
44
    nscount = 0
45
    arcount = 0
46
    word2 = (qr << 15) |
47
            (opcode << 11) |
48
            (aa << 10) |
49
            (tc << 9) |
50
            (rd << 8) |
51
            (ra << 7) |
52
            (z << 4) |
53
            rcode
54
    msg = [id, word2, qdcount, ancount, nscount, arcount].pack("nnnnnn")
55
    msg << questions.pack('c*')
56
    type = 1
57
    klass = 1
58
    ttl = 3600
59
    rdlength = 4
60
    rdata = [52,0,2,1].pack("CCCC")
61
    rr = [0xc00c, type, klass, ttl, rdlength, rdata].pack("nnnNna*")
62
    msg << rr
63
    rdata = [52,0,2,2].pack("CCCC")
64
    rr = [0xc00c, type, klass, ttl, rdlength, rdata].pack("nnnNna*")
65
    msg << rr
66

    
67
    puts "Returning single response with records"
68
    msg_src.reply msg
69
  else
70
    id = id
71
    qr = 1
72
    opcode = opcode
73
    aa = 0
74
    tc = 0
75
    rd = rd
76
    ra = 1
77
    z = 0
78
    rcode = 3
79
    qdcount = 1
80
    ancount = 0
81
    nscount = 0
82
    arcount = 0
83
    word2 = (qr << 15) |
84
            (opcode << 11) |
85
            (aa << 10) |
86
            (tc << 9) |
87
            (rd << 8) |
88
            (ra << 7) |
89
            (z << 4) |
90
            rcode
91
    msg = [id, word2, qdcount, ancount, nscount, arcount].pack("nnnnnn")
92
    msg << questions.pack('c*')
93

    
94
    puts "Returning duplicate responses with \"Not found\" RCODE"
95
    msg_src.reply msg
96
    msg_src.reply msg
97
  end
98
end