-
Notifications
You must be signed in to change notification settings - Fork 7
/
tuns-server
executable file
·324 lines (308 loc) · 9.08 KB
/
tuns-server
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
#!/usr/bin/ruby
# Tuns -- prototype of an IP over DNS tunnel
# Copyright (C) 2007 Lucas Nussbaum <[email protected]>
#
# 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/>.
$:.unshift File.join(File.dirname(__FILE__), '..', 'lib')
$:.unshift File.join(File.dirname(__FILE__), '..', 'lib', 'tuns')
require 'rbconfig'
$:.unshift File.join(RbConfig::CONFIG['rubylibdir'], 'tuns')
require 'socket'
require 'timeout'
require 'thread'
require 'optparse'
require 'date'
require 'tuns/tun'
require 'Net/DNS'
require 'tuns/dns'
PKTSIZE=2000
MAX_SLEEP=1.5
$max_sleep=MAX_SLEEP
$bindaddr='0.0.0.0'
$bindport=53
$ip="192.168.53.2"
$rip="192.168.53.1"
$domain=nil
$mtu=nil
$debug = false
$dnums = {}
progname = File::basename($PROGRAM_NAME)
opts = OptionParser::new do |opts|
opts.program_name = progname
opts.banner = "Usage: #{progname} [options]"
opts.separator ""
opts.separator "Mandatory options:"
opts.on("-d", "--domain DOMAIN", "Domain name to use to send/receive data") do |n|
$domain = n
end
opts.separator "Verbosity options:"
opts.on("", "--debug", "Debug mode") do |d|
$debug = true
$quiet = false
end
opts.separator ""
opts.separator "Overriding default values:"
opts.on("-m", "--mtu MTU", "MTU for tun device (overrides default calculation based on domain names)") do |m|
$mtu = m.to_i
end
opts.on("-b", "--bind-address ADDR", "Address to bind to. By default, binds to 0.0.0.0 (all interfaces)") do |s|
$bindaddr = s
end
opts.on("-p", "--bind-port PORT", "Port to bind to. By default, binds to port 53") do |s|
$bindport = s
end
opts.on("-i", "--ip", "IP for tun device") do |i|
$ip = i
end
opts.on("-t", "--remote-ip", "IP for other endpoint on tun") do |i|
$rip = i
end
end
begin
opts.parse!(ARGV)
rescue OptionParser::ParseError => pe
opts.warn pe
puts opts
exit 1
end
if $domain.nil?
puts "ERROR: Domain to send and receive data (--domain) must be specified."
puts
puts opts
exit 1
end
# creates and configure tun device
if $mtu.nil?
$mtu = 140 # FIXME
end
$tun = File::new('/dev/net/tun', File::RDWR)
$dev = tun_allocate($tun)
def reset_interface
system("ifconfig #{$dev} #{$ip} mtu #{$mtu} up")
end
reset_interface
system("route add -host #{$rip} dev #{$dev}")
# creates and configure listening socket
UDPSocket.do_not_reverse_lookup = true
$socket = UDPSocket.new
$socket.bind($bindaddr, $bindport)
# queue of packets to send
$queue = []
# queue of reqs for data
$reqqueue = []
$qmutex = Mutex::new
$need_send = ConditionVariable::new
# thread that reads from tun and writes to queue
$th_readtun = Thread::new($socket, $tun) do |socket, tun|
Thread::current.abort_on_exception = true
while (s = tun.sysread(PKTSIZE))
if s.length > $mtu
puts "#{DateTime::now.to_s} Packet too long (#{s.length}) !!"
exit(1)
end
packet = dns_encode(s)
$qmutex.synchronize do
$queue.push(packet)
$need_send.signal
end
end
end
# function to build reply to query
def build_reply(q)
quest = q.question[0]
rep = Net::DNS::Packet::new_from_values(quest.qname, quest.qtype, 'IN')
rep.header.id = q.header.id
rep.header.opcode = q.header.opcode
rep.header.aa = 1
rep.header.qr = 1 # response
rep.header.rd = q.header.rd
rep.header.ra = 0
rep
end
$need_wakeup = ConditionVariable::new
# thread that sleeps and wakes up $th_writedns periodically
$th_sleep = Thread::new do
Thread::current.abort_on_exception = true
while true
sleep $max_sleep
$qmutex.synchronize do
# if there's no reply waiting, no need to wake me up.
if $reqqueue.length == 0
$need_wakeup.wait($qmutex)
end
$need_send.signal
end
end
end
# thread that reads from reqqueue and send replies
$th_writedns = Thread::new($socket) do |socket|
Thread::current.abort_on_exception = true
while true
rep = nil
sender_addr = nil
sender_port = nil
$qmutex.synchronize do
# puts "<---"
# $reqqueue.each do |e|
# puts "#{e[0].qname} #{e[2]} #{e[3]} #{e[4]}"
# end
# puts "--->"
if $queue.length == 0
if $reqqueue.length == 0
$need_send.wait($qmutex)
elsif (Time::now - $reqqueue[0][4]) > $max_sleep
# we need to send a zero packet
q, rep, sender_addr, sender_port, age = $reqqueue.shift
rep.answer << Net::DNS::RR::new_from_hash(
:name => q.qname,
:ttl => 0,
:type => 'CNAME',
:cls => 'IN',
:cname => "dzero.#{$domain}"
)
else
$need_send.wait($qmutex)
end
else
# something to send
if $reqqueue.length == 0
# we have to wait for a req packet
puts "#{DateTime::now.to_s} Something to send, but no req!"
$need_send.wait($qmutex)
else
# we can send a data packet
q, rep, sender_addr, sender_port, age = $reqqueue.shift
num = q.qname.gsub(/^r(\d+)\..*/, '\1').to_i
if $dnums[num]
# duplicate download request. we resend the previous answer.
puts "#{DateTime::now.to_s} Duplicate download request received: #{num} (from #{sender_addr})"
rep.answer << $dnums[num]
else
text = $queue.shift
ans = Net::DNS::RR::new_from_hash(
:name => q.qname,
:ttl => 0,
:type => 'CNAME',
:cls => 'IN',
:cname => "d#{text}.#{$domain}"
)
# FIXME cache cleanup
$dnums[num] = ans
rep.answer << ans
end
end
end
end
next if rep.nil?
rep.header.ancount = 1
if $debug
puts "*" * 25 + 'SENDING DATA' + '*' * 25
p rep
end
socket.send(rep.data, 0, sender_addr, sender_port)
end
end
# thread that reads from socket and writes to tun
$th_readdns = Thread::new($socket, $tun) do |socket, tun|
Thread::current.abort_on_exception = true
while recvdata = socket.recvfrom(PKTSIZE)
rpack, sender = recvdata
dnsp = Net::DNS::Packet::new_from_binary(rpack)
q = dnsp.question[0]
if $debug
puts "*" * 25 + 'RECEIVED' + '*' * 25
p dnsp
end
rep = build_reply(dnsp)
if q.qname =~ /\.#{$domain}$/
text = q.qname.gsub(/\.#{$domain}$/, '')
if text[0..0] == 'd' and q.qtype == 'CNAME'
# we are receiving a packet
text = text[1..-1]
pack = dns_decode(text)
tun.syswrite(pack)
tun.flush
length = $qmutex.synchronize { $queue.length }
rep.answer << Net::DNS::RR::new_from_hash(
:name => q.qname,
:ttl => 0,
:type => 'CNAME',
:cls => 'IN',
:cname => "l#{length}.#{$domain}"
)
rep.header.ancount = 1
elsif text[0..0] == 'r' and q.qtype == 'CNAME'
# we are given the chance to send something!
$qmutex.synchronize do
$reqqueue.push([q, rep, sender[3], sender[1], Time::now])
$need_wakeup.signal
$need_send.signal
end
next
elsif text[0..0] == 'c' and q.qtype == 'A'
# config changes
text = text[1..-1]
conf = text.split('.')
ok = false
case conf[0]
when 'reset' then
$max_sleep = MAX_SLEEP
$dnums = {}
puts "Reset all defaults"
ok = true
when 'maxsleep' then
$max_sleep = conf[1].to_f / 1000
puts "Set $max_sleep to #{$max_sleep}"
ok = true
when 'mtu' then
$mtu = conf[1].to_i
puts "Set $mtu to #{$mtu}"
ok = true
reset_interface
end
if ok
rep.answer << Net::DNS::RR::new_from_hash(
:name => q.qname,
:ttl => 0,
:type => 'A',
:cls => 'IN',
:address => "1.2.3.4"
)
else
rep.answer << Net::DNS::RR::new_from_hash(
:name => q.qname,
:ttl => 0,
:type => 'A',
:cls => 'IN',
:address => "4.3.2.1"
)
end
rep.header.ancount = 1
else
puts "#{DateTime::now.to_s} Correct domain, invalid packet type: #{q.qtype} #{q.qname} (from #{sender[2]} - #{sender[3]})"
end
else
puts "#{DateTime::now.to_s} Invalid packet type: #{q.qtype} #{q.qname} (from #{sender[2]} - #{sender[3]})"
next
end
if $debug
puts "*" * 25 + 'SENDING' + '*' * 25
p rep
end
socket.send(rep.data, 0, sender[3], sender[1])
end
end
# wait for all threads to finish
$th_readtun.join
$th_readdns.join