ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/gvpe/src/vpn_dns.C
Revision: 1.40
Committed: Sat Jul 9 20:29:29 2005 UTC (18 years, 10 months ago) by pcg
Content type: text/plain
Branch: MAIN
CVS Tags: rel-2_0
Changes since 1.39: +2 -0 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 /*
2 vpn_dns.C -- handle the dns tunnel part of the protocol.
3 Copyright (C) 2003-2005 Marc Lehmann <gvpe@schmorp.de>
4
5 This file is part of GVPE.
6
7 GVPE is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with gvpe; if not, write to the Free Software
19 Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 // TODO: EDNS0 option to increase dns mtu?
23 // TODO: re-write dns packet parsing/creation using a safe mem-buffer
24 // to ensure no buffer overflows or similar problems.
25
26 #include "config.h"
27
28 #if ENABLE_DNS
29
30 // dns processing is EXTREMELY ugly. For obvious(?) reasons.
31 // it's a hack, use only in emergency situations please.
32
33 #include <cstring>
34 #include <cassert>
35
36 #include <sys/types.h>
37 #include <sys/socket.h>
38 #include <sys/wait.h>
39 #include <sys/uio.h>
40 #include <errno.h>
41 #include <time.h>
42 #include <unistd.h>
43 #include <fcntl.h>
44
45 #include <map>
46
47 #include <gmp.h>
48
49 #include "netcompat.h"
50
51 #include "vpn.h"
52
53 #define MAX_POLL_INTERVAL 5. // how often to poll minimally when the server has no data
54 #define ACTIVITY_INTERVAL 5.
55
56 #define INITIAL_TIMEOUT 0.1 // retry timeouts
57 #define INITIAL_SYN_TIMEOUT 2. // retry timeout for initial syn
58
59 #define MAX_SEND_INTERVAL 2. // optimistic?
60
61 #define MAX_WINDOW 1000 // max. for MAX_OUTSTANDING, and backlog
62 #define MAX_BACKLOG (64*1024) // size of gvpe protocol backlog (bytes), must be > MAXSIZE
63
64 #define MAX_DOMAIN_SIZE 240 // 255 is legal limit, but bind doesn't compress well
65 // 240 leaves about 4 bytes of server reply data
66 // every request byte less give room for two reply bytes
67
68 #define SEQNO_MASK 0x3fff
69 #define SEQNO_EQ(a,b) ( 0 == ( ((a) ^ (b)) & SEQNO_MASK) )
70
71 #define MAX_LBL_SIZE 63
72 #define MAX_PKT_SIZE 512
73
74 #define RR_TYPE_A 1
75 #define RR_TYPE_NULL 10
76 #define RR_TYPE_TXT 16
77 #define RR_TYPE_ANY 255
78
79 #define RR_CLASS_IN 1
80
81 #define CMD_IP_1 207
82 #define CMD_IP_2 46
83 #define CMD_IP_3 236
84 #define CMD_IP_RST 29
85 #define CMD_IP_SYN 113
86 #define CMD_IP_REJ 32
87
88 // works for cmaps up to 255 (not 256!)
89 struct charmap
90 {
91 enum { INVALID = (u8)255 };
92
93 char encode [256]; // index => char
94 u8 decode [256]; // char => index
95 unsigned int size;
96
97 charmap (const char *cmap);
98 };
99
100 charmap::charmap (const char *cmap)
101 {
102 char *enc = encode;
103 u8 *dec = decode;
104
105 memset (enc, (char) 0, 256);
106 memset (dec, (char)INVALID, 256);
107
108 for (size = 0; cmap [size]; size++)
109 {
110 enc [size] = cmap [size];
111 dec [(u8)enc [size]] = size;
112 }
113
114 assert (size < 256);
115 }
116
117 #define MAX_DEC_LEN 500
118 #define MAX_ENC_LEN (MAX_DEC_LEN * 2)
119 #define MAX_LIMBS ((MAX_DEC_LEN * 8 + GMP_NUMB_BITS - 1) / GMP_NUMB_BITS)
120
121 // ugly. minimum base is 16(!)
122 struct basecoder
123 {
124 charmap cmap;
125 unsigned int enc_len [MAX_DEC_LEN];
126 unsigned int dec_len [MAX_ENC_LEN];
127
128 unsigned int encode_len (unsigned int len);
129 unsigned int decode_len (unsigned int len);
130
131 unsigned int encode (char *dst, u8 *src, unsigned int len);
132 unsigned int decode (u8 *dst, char *src, unsigned int len);
133
134 basecoder (const char *cmap);
135 };
136
137 basecoder::basecoder (const char *cmap)
138 : cmap (cmap)
139 {
140 for (unsigned int len = 0; len < MAX_DEC_LEN; ++len)
141 {
142 u8 src [MAX_DEC_LEN];
143 u8 dst [MAX_ENC_LEN];
144
145 memset (src, 255, len);
146
147 mp_limb_t m [MAX_LIMBS];
148 mp_size_t n;
149
150 n = mpn_set_str (m, src, len, 256);
151 n = mpn_get_str (dst, this->cmap.size, m, n);
152
153 for (int i = 0; !dst [i]; ++i)
154 n--;
155
156 enc_len [len] = n;
157 dec_len [n] = len;
158 }
159 }
160
161 unsigned int basecoder::encode_len (unsigned int len)
162 {
163 return enc_len [len];
164 }
165
166 unsigned int basecoder::decode_len (unsigned int len)
167 {
168 while (len && !dec_len [len])
169 --len;
170
171 return dec_len [len];
172 }
173
174 unsigned int basecoder::encode (char *dst, u8 *src, unsigned int len)
175 {
176 if (!len || len > MAX_DEC_LEN)
177 return 0;
178
179 int elen = encode_len (len);
180
181 mp_limb_t m [MAX_LIMBS];
182 mp_size_t n;
183
184 u8 dst_ [MAX_ENC_LEN];
185
186 n = mpn_set_str (m, src, len, 256);
187 n = mpn_get_str (dst_, cmap.size, m, n);
188
189 int plen = elen; // for padding
190
191 while (n < plen)
192 {
193 *dst++ = cmap.encode [0];
194 plen--;
195 }
196
197 for (unsigned int i = n - plen; i < n; ++i)
198 *dst++ = cmap.encode [dst_ [i]];
199
200 return elen;
201 }
202
203 unsigned int basecoder::decode (u8 *dst, char *src, unsigned int len)
204 {
205 if (!len || len > MAX_ENC_LEN)
206 return 0;
207
208 u8 src_ [MAX_ENC_LEN];
209 unsigned int elen = 0;
210
211 while (len--)
212 {
213 u8 val = cmap.decode [(u8)*src++];
214
215 if (val != charmap::INVALID)
216 src_ [elen++] = val;
217 }
218
219 int dlen = decode_len (elen);
220
221 mp_limb_t m [MAX_LIMBS];
222 mp_size_t n;
223
224 u8 dst_ [MAX_DEC_LEN];
225
226 n = mpn_set_str (m, src_, elen, cmap.size);
227 n = mpn_get_str (dst_, 256, m, n);
228
229 if (n < dlen)
230 {
231 memset (dst, 0, dlen - n);
232 memcpy (dst + dlen - n, dst_, n);
233 }
234 else
235 memcpy (dst, dst_ + n - dlen, dlen);
236
237 return dlen;
238 }
239
240 #if 0
241 struct test { test (); } test;
242
243 test::test ()
244 {
245 basecoder cdc ("0123456789abcdefghijklmnopqrstuvwxyz");
246
247 u8 in[] = "0123456789abcdefghijklmnopqrstuvwxyz";
248 static char enc[200];
249 static u8 dec[200];
250
251 for (int i = 1; i < 20; i++)
252 {
253 int elen = cdc.encode (enc, in, i);
254 int dlen = cdc.decode (dec, enc, elen);
255
256 printf ("%d>%d>%d (%s>%s)\n", i, elen, dlen, enc, dec);
257 }
258 abort ();
259 }
260 #endif
261
262 //static basecoder cdc64 ("_dDpPhHzZrR06QqMmjJkKBb34TtSsvVlL81xXaAeEFf92WwGgYyoO57UucCNniI-");
263 //static basecoder cdc63 ("_dDpPhHzZrR06QqMmjJkKBb34TtSsvVlL81xXaAeEFf92WwGgYyoO57UucCNniI");
264 static basecoder cdc62 ("dDpPhHzZrR06QqMmjJkKBb34TtSsvVlL81xXaAeEFf92WwGgYyoO57UucCNniI");
265 //static basecoder cdc36 ("dphzr06qmjkb34tsvl81xaef92wgyo57ucni"); // unused as of yet
266 static basecoder cdc26 ("dPhZrQmJkBtSvLxAeFwGyO");
267
268 /////////////////////////////////////////////////////////////////////////////
269
270 #define HDRSIZE 6
271
272 inline void encode_header (char *data, int clientid, int seqno, int retry = 0)
273 {
274 seqno &= SEQNO_MASK;
275
276 u8 hdr[3] = {
277 clientid,
278 (seqno >> 8) | (retry << 6),
279 seqno,
280 };
281
282 assert (clientid < 256);
283
284 cdc26.encode (data, hdr, 3);
285 }
286
287 inline void decode_header (char *data, int &clientid, int &seqno)
288 {
289 u8 hdr[3];
290
291 cdc26.decode (hdr, data, HDRSIZE);
292
293 clientid = hdr[0];
294 seqno = ((hdr[1] << 8) | hdr[2]) & SEQNO_MASK;
295 }
296
297 /////////////////////////////////////////////////////////////////////////////
298
299 struct byte_stream
300 {
301 u8 *data;
302 int maxsize;
303 int fill;
304
305 byte_stream (int maxsize);
306 ~byte_stream ();
307
308 bool empty () { return !fill; }
309 int size () { return fill; }
310
311 bool put (u8 *data, unsigned int datalen);
312 bool put (vpn_packet *pkt);
313 vpn_packet *get ();
314
315 u8 *begin () { return data; }
316 void remove (int count);
317 };
318
319 byte_stream::byte_stream (int maxsize)
320 : maxsize (maxsize), fill (0)
321 {
322 data = new u8 [maxsize];
323 }
324
325 byte_stream::~byte_stream ()
326 {
327 delete data;
328 }
329
330 void byte_stream::remove (int count)
331 {
332 if (count > fill)
333 assert (count <= fill);
334
335 memmove (data, data + count, fill -= count);
336 }
337
338 bool byte_stream::put (u8 *data, unsigned int datalen)
339 {
340 if (maxsize - fill < datalen)
341 return false;
342
343 memcpy (this->data + fill, data, datalen); fill += datalen;
344
345 return true;
346 }
347
348 bool byte_stream::put (vpn_packet *pkt)
349 {
350 if (maxsize - fill < pkt->len + 2)
351 return false;
352
353 data [fill++] = pkt->len >> 8;
354 data [fill++] = pkt->len;
355
356 memcpy (data + fill, pkt->at (0), pkt->len); fill += pkt->len;
357
358 return true;
359 }
360
361 vpn_packet *byte_stream::get ()
362 {
363 unsigned int len;
364
365 for (;;)
366 {
367 len = (data [0] << 8) | data [1];
368
369 if (len <= MAXSIZE || fill < 2)
370 break;
371
372 // TODO: handle this better than skipping, e.g. by reset
373 slog (L_DEBUG, _("DNS: corrupted packet stream skipping a byte..."));
374 remove (1);
375 }
376
377 if (fill < len + 2)
378 return 0;
379
380 vpn_packet *pkt = new vpn_packet;
381
382 pkt->len = len;
383 memcpy (pkt->at (0), data + 2, len);
384 remove (len + 2);
385
386 return pkt;
387 }
388
389 /////////////////////////////////////////////////////////////////////////////
390
391 #define FLAG_QUERY ( 0 << 15)
392 #define FLAG_RESPONSE ( 1 << 15)
393 #define FLAG_OP_MASK (15 << 11)
394 #define FLAG_OP_QUERY ( 0 << 11)
395 #define FLAG_AA ( 1 << 10)
396 #define FLAG_TC ( 1 << 9)
397 #define FLAG_RD ( 1 << 8)
398 #define FLAG_RA ( 1 << 7)
399 #define FLAG_AUTH ( 1 << 5)
400 #define FLAG_RCODE_MASK (15 << 0)
401 #define FLAG_RCODE_OK ( 0 << 0)
402 #define FLAG_RCODE_FORMERR ( 1 << 0)
403 #define FLAG_RCODE_SERVFAIL ( 2 << 0)
404 #define FLAG_RCODE_NXDOMAIN ( 3 << 0)
405 #define FLAG_RCODE_REFUSED ( 5 << 0)
406
407 #define DEFAULT_CLIENT_FLAGS (FLAG_QUERY | FLAG_OP_QUERY | FLAG_RD)
408 #define DEFAULT_SERVER_FLAGS (FLAG_RESPONSE | FLAG_OP_QUERY | FLAG_AA | FLAG_RD | FLAG_RA)
409
410 struct dns_cfg
411 {
412 static int next_uid;
413
414 u8 id1, id2, id3, id4;
415
416 u8 version;
417 u8 flags;
418 u8 rrtype;
419 u8 def_ttl;
420
421 u16 client;
422 u16 uid; // to make request unique
423
424 u16 max_size;
425 u8 seq_cdc;
426 u8 req_cdc;
427
428 u8 rep_cdc;
429 u8 delay; // time in 0.01s units that the server may delay replying packets
430 u8 r3, r4;
431
432 u8 r5, r6, r7, r8;
433
434 void reset (int clientid);
435 bool valid ();
436 };
437
438 int dns_cfg::next_uid;
439
440 void dns_cfg::reset (int clientid)
441 {
442 id1 = 'G';
443 id2 = 'V';
444 id3 = 'P';
445 id4 = 'E';
446
447 version = 1;
448
449 rrtype = RR_TYPE_TXT;
450 flags = 0;
451 def_ttl = 0;
452 seq_cdc = 26;
453 req_cdc = 62;
454 rep_cdc = 0;
455 max_size = htons (MAX_PKT_SIZE);
456 client = htons (clientid);
457 uid = next_uid++;
458 delay = 0;
459
460 r3 = r4 = 0;
461 r4 = r5 = r6 = r7 = 0;
462 }
463
464 bool dns_cfg::valid ()
465 {
466 // although the protocol itself allows for some configurability,
467 // only the following encoding/decoding settings are implemented.
468 return id1 == 'G'
469 && id2 == 'V'
470 && id3 == 'P'
471 && id4 == 'E'
472 && seq_cdc == 26
473 && req_cdc == 62
474 && rep_cdc == 0
475 && version == 1;
476 }
477
478 struct dns_packet : net_packet
479 {
480 u16 id;
481 u16 flags; // QR:1 Opcode:4 AA:1 TC:1 RD:1 RA:1 Z:3 RCODE:4
482 u16 qdcount, ancount, nscount, arcount;
483
484 u8 data [MAXSIZE - 6 * 2];
485
486 int decode_label (char *data, int size, int &offs);
487 };
488
489 int dns_packet::decode_label (char *data, int size, int &offs)
490 {
491 char *orig = data;
492
493 memset (data, 0, size);
494
495 while (offs < size - 1)
496 {
497 u8 len = (*this)[offs++];
498
499 if (!len)
500 break;
501 else if (len < 64)
502 {
503 if (size < len + 1 || offs + len >= MAXSIZE - 1)
504 break;
505
506 memcpy (data, &((*this)[offs]), len);
507
508 data += len; size -= len; offs += len;
509 *data++ = '.'; size--;
510 }
511 else
512 {
513 int offs2 = ((len & 63) << 8) + (*this)[offs++];
514
515 data += decode_label (data, size, offs2);
516 break;
517 }
518 }
519
520 return data - orig;
521 }
522
523 /////////////////////////////////////////////////////////////////////////////
524
525 static u16 dns_id = 0; // TODO: should be per-vpn
526
527 static u16 next_id ()
528 {
529 if (!dns_id)
530 dns_id = time (0);
531
532 // the simplest lsfr with periodicity 65535 i could find
533 dns_id = (dns_id << 1)
534 | (((dns_id >> 1)
535 ^ (dns_id >> 2)
536 ^ (dns_id >> 4)
537 ^ (dns_id >> 15)) & 1);
538
539 return dns_id;
540 }
541
542 struct dns_rcv;
543 struct dns_snd;
544
545 struct dns_connection
546 {
547 connection *c;
548 struct vpn *vpn;
549
550 dns_cfg cfg;
551
552 bool established;
553
554 tstamp last_received;
555 tstamp last_sent;
556 double min_latency;
557 double poll_interval, send_interval;
558
559 vector<dns_rcv *> rcvpq;
560
561 byte_stream rcvdq; int rcvseq; int repseq;
562 byte_stream snddq; int sndseq;
563
564 void time_cb (time_watcher &w); time_watcher tw;
565 void receive_rep (dns_rcv *r);
566
567 dns_connection (connection *c);
568 ~dns_connection ();
569 };
570
571 struct dns_snd
572 {
573 dns_packet *pkt;
574 tstamp timeout, sent;
575 int retry;
576 struct dns_connection *dns;
577 int seqno;
578 bool stdhdr;
579
580 void gen_stream_req (int seqno, byte_stream &stream);
581 void gen_syn_req ();
582
583 dns_snd (dns_connection *dns);
584 ~dns_snd ();
585 };
586
587 dns_snd::dns_snd (dns_connection *dns)
588 : dns (dns)
589 {
590 timeout = 0;
591 retry = 0;
592 seqno = 0;
593 sent = NOW;
594 stdhdr = false;
595
596 pkt = new dns_packet;
597
598 pkt->id = next_id ();
599 }
600
601 dns_snd::~dns_snd ()
602 {
603 delete pkt;
604 }
605
606 static void append_domain (dns_packet &pkt, int &offs, const char *domain)
607 {
608 // add tunnel domain
609 for (;;)
610 {
611 const char *end = strchr (domain, '.');
612
613 if (!end)
614 end = domain + strlen (domain);
615
616 int len = end - domain;
617
618 pkt [offs++] = len;
619 memcpy (pkt.at (offs), domain, len);
620 offs += len;
621
622 if (!*end)
623 break;
624
625 domain = end + 1;
626 }
627 }
628
629 void dns_snd::gen_stream_req (int seqno, byte_stream &stream)
630 {
631 stdhdr = true;
632 this->seqno = seqno;
633
634 timeout = NOW + INITIAL_TIMEOUT;
635
636 pkt->flags = htons (DEFAULT_CLIENT_FLAGS);
637 pkt->qdcount = htons (1);
638
639 int offs = 6*2;
640 int dlen = MAX_DOMAIN_SIZE - (strlen (dns->c->conf->domain) + 2);
641 // MAX_DOMAIN_SIZE is technically 255, but bind doesn't compress responses well,
642 // so we need to have space for 2*MAX_DOMAIN_SIZE + header + extra
643
644 char enc[256], *encp = enc;
645 encode_header (enc, THISNODE->id, seqno);
646
647 int datalen = cdc62.decode_len (dlen - (dlen + MAX_LBL_SIZE - 1) / MAX_LBL_SIZE - HDRSIZE);
648
649 if (datalen > stream.size ())
650 datalen = stream.size ();
651
652 int enclen = cdc62.encode (enc + HDRSIZE, stream.begin (), datalen) + HDRSIZE;
653 stream.remove (datalen);
654
655 while (enclen)
656 {
657 int lbllen = enclen < MAX_LBL_SIZE ? enclen : MAX_LBL_SIZE;
658
659 (*pkt)[offs++] = lbllen;
660 memcpy (pkt->at (offs), encp, lbllen);
661
662 offs += lbllen;
663 encp += lbllen;
664
665 enclen -= lbllen;
666 }
667
668 append_domain (*pkt, offs, dns->c->conf->domain);
669
670 (*pkt)[offs++] = 0;
671 (*pkt)[offs++] = RR_TYPE_ANY >> 8; (*pkt)[offs++] = RR_TYPE_ANY;
672 (*pkt)[offs++] = RR_CLASS_IN >> 8; (*pkt)[offs++] = RR_CLASS_IN;
673
674 pkt->len = offs;
675 }
676
677 void dns_snd::gen_syn_req ()
678 {
679 timeout = NOW + INITIAL_SYN_TIMEOUT;
680
681 pkt->flags = htons (DEFAULT_CLIENT_FLAGS);
682 pkt->qdcount = htons (1);
683
684 int offs = 6 * 2;
685
686 int elen = cdc26.encode ((char *)pkt->at (offs + 1), (u8 *)&dns->cfg, sizeof (dns_cfg));
687
688 assert (elen <= MAX_LBL_SIZE);
689
690 (*pkt)[offs] = elen;
691 offs += elen + 1;
692 append_domain (*pkt, offs, dns->c->conf->domain);
693
694 (*pkt)[offs++] = 0;
695 (*pkt)[offs++] = RR_TYPE_A >> 8; (*pkt)[offs++] = RR_TYPE_A;
696 (*pkt)[offs++] = RR_CLASS_IN >> 8; (*pkt)[offs++] = RR_CLASS_IN;
697
698 pkt->len = offs;
699 }
700
701 struct dns_rcv
702 {
703 int seqno;
704 dns_packet *pkt; // reply packet
705 u8 data [MAXSIZE]; // actually part of the reply packet...
706 int datalen;
707
708 dns_rcv (int seqno, u8 *data, int datalen);
709 ~dns_rcv ();
710 };
711
712 dns_rcv::dns_rcv (int seqno, u8 *data, int datalen)
713 : seqno (seqno), pkt (new dns_packet), datalen (datalen)
714 {
715 memcpy (this->data, data, datalen);
716 }
717
718 dns_rcv::~dns_rcv ()
719 {
720 delete pkt;
721 }
722
723 /////////////////////////////////////////////////////////////////////////////
724
725 dns_connection::dns_connection (connection *c)
726 : c (c)
727 , rcvdq (MAX_BACKLOG * 2)
728 , snddq (MAX_BACKLOG)
729 , tw (this, &dns_connection::time_cb)
730 {
731 vpn = c->vpn;
732
733 established = false;
734
735 rcvseq = repseq = sndseq = 0;
736
737 last_sent = last_received = 0;
738 poll_interval = 0.5; // starting here
739 send_interval = 0.5; // starting rate
740 min_latency = INITIAL_TIMEOUT;
741 }
742
743 dns_connection::~dns_connection ()
744 {
745 for (vector<dns_rcv *>::iterator i = rcvpq.begin ();
746 i != rcvpq.end ();
747 ++i)
748 delete *i;
749 }
750
751 void dns_connection::receive_rep (dns_rcv *r)
752 {
753 if (r->datalen)
754 {
755 last_received = NOW;
756 tw.trigger ();
757
758 poll_interval = send_interval;
759 }
760 else
761 {
762 poll_interval *= 1.5;
763
764 if (poll_interval > MAX_POLL_INTERVAL)
765 poll_interval = MAX_POLL_INTERVAL;
766 }
767
768 rcvpq.push_back (r);
769
770 redo:
771
772 // find next packet
773 for (vector<dns_rcv *>::iterator i = rcvpq.end (); i-- != rcvpq.begin (); )
774 if (SEQNO_EQ (rcvseq, (*i)->seqno))
775 {
776 // enter the packet into our input stream
777 r = *i;
778
779 // remove the oldest packet, look forward, as it's oldest first
780 for (vector<dns_rcv *>::iterator j = rcvpq.begin (); j != rcvpq.end (); ++j)
781 if (SEQNO_EQ ((*j)->seqno, rcvseq - MAX_WINDOW))
782 {
783 delete *j;
784 rcvpq.erase (j);
785 break;
786 }
787
788 rcvseq = (rcvseq + 1) & SEQNO_MASK;
789
790 if (!rcvdq.put (r->data, r->datalen))
791 {
792 slog (L_ERR, "DNS: !rcvdq.put (r->data, r->datalen)");
793 abort (); // MUST never overflow, can be caused by data corruption, TODO
794 }
795
796 while (vpn_packet *pkt = rcvdq.get ())
797 {
798 sockinfo si;
799 si.host = htonl (c->conf->id); si.port = 0; si.prot = PROT_DNSv4;
800
801 vpn->recv_vpn_packet (pkt, si);
802
803 delete pkt;
804 }
805
806 // check for further packets
807 goto redo;
808 }
809 }
810
811 void
812 vpn::dnsv4_server (dns_packet &pkt)
813 {
814 u16 flags = ntohs (pkt.flags);
815
816 int offs = 6 * 2; // skip header
817
818 pkt.flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_FORMERR);
819
820 if (0 == (flags & (FLAG_RESPONSE | FLAG_OP_MASK))
821 && pkt.qdcount == htons (1))
822 {
823 char qname [MAXSIZE];
824 int qlen = pkt.decode_label ((char *)qname, MAXSIZE - offs, offs);
825
826 u16 qtype = pkt [offs++] << 8; qtype |= pkt [offs++];
827 u16 qclass = pkt [offs++] << 8; qclass |= pkt [offs++];
828
829 pkt.qdcount = htons (1);
830 pkt.ancount = 0;
831 pkt.nscount = 0; // should be self, as other nameservers reply like this
832 pkt.arcount = 0; // a record for self, as other nameservers reply like this
833
834 pkt.flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_SERVFAIL);
835
836 int dlen = strlen (THISNODE->domain);
837
838 if (qclass == RR_CLASS_IN
839 && qlen > dlen + 1
840 && !memcmp (qname + qlen - (dlen + 1), THISNODE->domain, dlen))
841 {
842 // now generate reply
843 pkt.ancount = htons (1); // one answer RR
844 pkt.flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_OK);
845
846 if ((qtype == RR_TYPE_ANY
847 || qtype == RR_TYPE_TXT
848 || qtype == RR_TYPE_NULL)
849 && qlen > dlen + 1 + HDRSIZE)
850 {
851 // correct class, domain: parse
852 int client, seqno;
853 decode_header (qname, client, seqno);
854
855 u8 data[MAXSIZE];
856 int datalen = cdc62.decode (data, qname + HDRSIZE, qlen - (dlen + 1 + HDRSIZE));
857
858 if (0 < client && client <= conns.size ())
859 {
860 connection *c = conns [client - 1];
861 dns_connection *dns = c->dns;
862 dns_rcv *rcv;
863
864 if (dns)
865 {
866 for (vector<dns_rcv *>::iterator i = dns->rcvpq.end (); i-- != dns->rcvpq.begin (); )
867 if (SEQNO_EQ ((*i)->seqno, seqno))
868 {
869 // already seen that request: simply reply with the cached reply
870 dns_rcv *r = *i;
871
872 slog (L_DEBUG, "DNS: duplicate packet received ID %d, SEQ %d", htons (r->pkt->id), seqno);
873
874 // refresh header & id, as the retry count could have changed
875 memcpy (r->pkt->at (6 * 2 + 1), pkt.at (6 * 2 + 1), HDRSIZE);
876 r->pkt->id = pkt.id;
877
878 memcpy (pkt.at (0), r->pkt->at (0), offs = r->pkt->len);
879
880 goto duplicate_request;
881 }
882
883 // new packet, queue
884 rcv = new dns_rcv (seqno, data, datalen);
885 dns->receive_rep (rcv);
886 }
887
888 {
889 pkt [offs++] = 0xc0; pkt [offs++] = 6 * 2; // refer to name in query section
890
891 int rtype = dns ? dns->cfg.rrtype : RR_TYPE_A;
892 pkt [offs++] = rtype >> 8; pkt [offs++] = rtype; // type
893 pkt [offs++] = RR_CLASS_IN >> 8; pkt [offs++] = RR_CLASS_IN; // class
894 pkt [offs++] = 0; pkt [offs++] = 0;
895 pkt [offs++] = 0; pkt [offs++] = dns ? dns->cfg.def_ttl : 0; // TTL
896
897 int rdlen_offs = offs += 2;
898
899 if (dns)
900 {
901 int dlen = ntohs (dns->cfg.max_size) - offs;
902
903 // bind doesn't compress well, so reduce further by one label length
904 dlen -= qlen;
905
906 // only put data into in-order sequence packets, if
907 // we receive out-of-order packets we generate empty
908 // replies
909 //printf ("%d - %d & %x (=%d) < %d\n", seqno, dns->repseq, SEQNO_MASK, (seqno - dns->repseq) & SEQNO_MASK, MAX_WINDOW);//D
910 if (((seqno - dns->repseq) & SEQNO_MASK) <= MAX_WINDOW)
911 {
912 dns->repseq = seqno;
913
914 while (dlen > 1 && !dns->snddq.empty ())
915 {
916 int txtlen = dlen <= 255 ? dlen - 1 : 255;
917
918 if (txtlen > dns->snddq.size ())
919 txtlen = dns->snddq.size ();
920
921 pkt[offs++] = txtlen;
922 memcpy (pkt.at (offs), dns->snddq.begin (), txtlen);
923 offs += txtlen;
924 dns->snddq.remove (txtlen);
925
926 dlen -= txtlen + 1;
927 }
928 }
929
930 // avoid completely empty TXT rdata
931 if (offs == rdlen_offs)
932 pkt[offs++] = 0;
933
934 slog (L_NOISE, "DNS: snddq %d", dns->snddq.size ());
935 }
936 else
937 {
938 // send RST
939 pkt [offs++] = CMD_IP_1; pkt [offs++] = CMD_IP_2; pkt [offs++] = CMD_IP_3;
940 pkt [offs++] = CMD_IP_RST;
941 }
942
943 int rdlen = offs - rdlen_offs;
944
945 pkt [rdlen_offs - 2] = rdlen >> 8;
946 pkt [rdlen_offs - 1] = rdlen;
947
948 if (dns)
949 {
950 // now update dns_rcv copy
951 rcv->pkt->len = offs;
952 memcpy (rcv->pkt->at (0), pkt.at (0), offs);
953 }
954 }
955
956 duplicate_request: ;
957 }
958 else
959 pkt.flags = htons (DEFAULT_SERVER_FLAGS | FLAG_RCODE_FORMERR);
960 }
961 else if (qtype == RR_TYPE_A
962 && qlen > dlen + 1 + cdc26.encode_len (sizeof (dns_cfg)))
963 {
964 dns_cfg cfg;
965 cdc26.decode ((u8 *)&cfg, qname, cdc26.encode_len (sizeof (dns_cfg)));
966 int client = ntohs (cfg.client);
967
968 pkt [offs++] = 0xc0; pkt [offs++] = 6 * 2; // refer to name in query section
969
970 pkt [offs++] = RR_TYPE_A >> 8; pkt [offs++] = RR_TYPE_A; // type
971 pkt [offs++] = RR_CLASS_IN >> 8; pkt [offs++] = RR_CLASS_IN; // class
972 pkt [offs++] = 0; pkt [offs++] = 0;
973 pkt [offs++] = 0; pkt [offs++] = cfg.def_ttl; // TTL
974 pkt [offs++] = 0; pkt [offs++] = 4; // rdlength
975
976 slog (L_INFO, _("DNS: client %d connects"), client);
977
978 pkt [offs++] = CMD_IP_1; pkt [offs++] = CMD_IP_2; pkt [offs++] = CMD_IP_3;
979 pkt [offs++] = CMD_IP_REJ;
980
981 if (0 < client && client <= conns.size ())
982 {
983 connection *c = conns [client - 1];
984
985 if (cfg.valid ())
986 {
987 pkt [offs - 1] = CMD_IP_SYN;
988
989 delete c->dns;
990 c->dns = new dns_connection (c);
991 c->dns->cfg = cfg;
992 }
993 }
994 }
995 }
996
997 pkt.len = offs;
998 }
999 }
1000
1001 void
1002 vpn::dnsv4_client (dns_packet &pkt)
1003 {
1004 u16 flags = ntohs (pkt.flags);
1005 int offs = 6 * 2; // skip header
1006
1007 pkt.qdcount = ntohs (pkt.qdcount);
1008 pkt.ancount = ntohs (pkt.ancount);
1009
1010 // go through our request list and find the corresponding request
1011 for (vector<dns_snd *>::iterator i = dns_sndpq.begin ();
1012 i != dns_sndpq.end ();
1013 ++i)
1014 if ((*i)->pkt->id == pkt.id)
1015 {
1016 dns_connection *dns = (*i)->dns;
1017 connection *c = dns->c;
1018 int seqno = (*i)->seqno;
1019 u8 data[MAXSIZE], *datap = data;
1020
1021 if ((*i)->retry)
1022 {
1023 dns->send_interval *= 1.01;
1024 if (dns->send_interval > MAX_SEND_INTERVAL)
1025 dns->send_interval = MAX_SEND_INTERVAL;
1026 }
1027 else
1028 {
1029 #if 0
1030 dns->send_interval *= 0.999;
1031 #endif
1032 // the latency surely puts an upper bound on
1033 // the minimum send interval
1034 double latency = NOW - (*i)->sent;
1035
1036 if (latency < dns->min_latency)
1037 dns->min_latency = latency;
1038
1039 if (dns->send_interval > dns->min_latency * conf.dns_overlap_factor)
1040 dns->send_interval = dns->min_latency * conf.dns_overlap_factor;
1041
1042 if (dns->send_interval < conf.dns_send_interval)
1043 dns->send_interval = conf.dns_send_interval;
1044 }
1045
1046 delete *i;
1047 dns_sndpq.erase (i);
1048
1049 if (flags & FLAG_RESPONSE && !(flags & FLAG_OP_MASK))
1050 {
1051 char qname[MAXSIZE];
1052
1053 while (pkt.qdcount-- && offs < MAXSIZE - 4)
1054 {
1055 int qlen = pkt.decode_label ((char *)qname, MAXSIZE - offs, offs);
1056 offs += 4; // skip qtype, qclass
1057 }
1058
1059 while (pkt.ancount-- && offs < MAXSIZE - 10 && datap)
1060 {
1061 int qlen = pkt.decode_label ((char *)qname, MAXSIZE - offs, offs);
1062
1063 u16 qtype = pkt [offs++] << 8; qtype |= pkt [offs++];
1064 u16 qclass = pkt [offs++] << 8; qclass |= pkt [offs++];
1065 u32 ttl = pkt [offs++] << 24;
1066 ttl |= pkt [offs++] << 16;
1067 ttl |= pkt [offs++] << 8;
1068 ttl |= pkt [offs++];
1069 u16 rdlen = pkt [offs++] << 8; rdlen |= pkt [offs++];
1070
1071 if (qtype == RR_TYPE_NULL || qtype == RR_TYPE_TXT)
1072 {
1073 if (rdlen <= MAXSIZE - offs)
1074 {
1075 // decode bytes, finally
1076
1077 while (rdlen)
1078 {
1079 int txtlen = pkt [offs++];
1080
1081 assert (txtlen + offs < MAXSIZE - 1);
1082
1083 memcpy (datap, pkt.at (offs), txtlen);
1084 datap += txtlen; offs += txtlen;
1085
1086 rdlen -= txtlen + 1;
1087 }
1088 }
1089 }
1090 else if (qtype == RR_TYPE_A)
1091 {
1092 u8 ip [4];
1093
1094 ip [0] = pkt [offs++];
1095 ip [1] = pkt [offs++];
1096 ip [2] = pkt [offs++];
1097 ip [3] = pkt [offs++];
1098
1099 if (ip [0] == CMD_IP_1
1100 && ip [1] == CMD_IP_2
1101 && ip [2] == CMD_IP_3)
1102 {
1103 slog (L_TRACE, _("DNS: got tunnel meta command %02x"), ip [3]);
1104
1105 if (ip [3] == CMD_IP_RST)
1106 {
1107 slog (L_DEBUG, _("DNS: got tunnel RST request"));
1108
1109 delete dns; c->dns = 0;
1110
1111 return;
1112 }
1113 else if (ip [3] == CMD_IP_SYN)
1114 {
1115 slog (L_DEBUG, _("DNS: got tunnel SYN reply, server likes us."));
1116 dns->established = true;
1117 }
1118 else if (ip [3] == CMD_IP_REJ)
1119 {
1120 slog (L_DEBUG, _("DNS: got tunnel REJ reply, server does not like us, aborting."));
1121 abort ();
1122 }
1123 else
1124 slog (L_INFO, _("DNS: got unknown meta command %02x"), ip [3]);
1125 }
1126 else
1127 slog (L_INFO, _("DNS: got spurious a record %d.%d.%d.%d"),
1128 ip [0], ip [1], ip [2], ip [3]);
1129
1130 return;
1131 }
1132
1133 int client, rseqno;
1134 decode_header (qname, client, rseqno);
1135
1136 if (client != THISNODE->id)
1137 {
1138 slog (L_INFO, _("DNS: got dns tunnel response with wrong clientid, ignoring"));
1139 datap = 0;
1140 }
1141 else if (rseqno != seqno)
1142 {
1143 slog (L_DEBUG, _("DNS: got dns tunnel response with wrong seqno, badly caching nameserver?"));
1144 datap = 0;
1145 }
1146 }
1147 }
1148
1149 // todo: pkt now used
1150 if (datap)
1151 dns->receive_rep (new dns_rcv (seqno, data, datap - data));
1152
1153 break;
1154 }
1155 }
1156
1157 void
1158 vpn::dnsv4_ev (io_watcher &w, short revents)
1159 {
1160 if (revents & EVENT_READ)
1161 {
1162 dns_packet *pkt = new dns_packet;
1163 struct sockaddr_in sa;
1164 socklen_t sa_len = sizeof (sa);
1165
1166 pkt->len = recvfrom (w.fd, pkt->at (0), MAXSIZE, 0, (sockaddr *)&sa, &sa_len);
1167
1168 if (pkt->len > 0)
1169 {
1170 if (ntohs (pkt->flags) & FLAG_RESPONSE)
1171 dnsv4_client (*pkt);
1172 else
1173 {
1174 dnsv4_server (*pkt);
1175 sendto (w.fd, pkt->at (0), pkt->len, 0, (sockaddr *)&sa, sa_len);
1176 }
1177
1178 delete pkt;
1179 }
1180 }
1181 }
1182
1183 bool
1184 vpn::send_dnsv4_packet (vpn_packet *pkt, const sockinfo &si, int tos)
1185 {
1186 int client = ntohl (si.host);
1187
1188 assert (0 < client && client <= conns.size ());
1189
1190 connection *c = conns [client - 1];
1191
1192 if (!c->dns)
1193 c->dns = new dns_connection (c);
1194
1195 if (c->dns->snddq.put (pkt))
1196 c->dns->tw.trigger ();
1197
1198 // always return true even if the buffer overflows
1199 return true;
1200 }
1201
1202 void
1203 connection::dnsv4_reset_connection ()
1204 {
1205 //delete dns; dns = 0; //TODO
1206 }
1207
1208 #define NEXT(w) do { if (next > (w)) next = w; } while (0)
1209
1210 void
1211 dns_connection::time_cb (time_watcher &w)
1212 {
1213 // servers have to be polled
1214 if (THISNODE->dns_port)
1215 return;
1216
1217 // check for timeouts and (re)transmit
1218 tstamp next = NOW + poll_interval;
1219 dns_snd *send = 0;
1220
1221 for (vector<dns_snd *>::iterator i = vpn->dns_sndpq.begin ();
1222 i != vpn->dns_sndpq.end ();
1223 ++i)
1224 {
1225 dns_snd *r = *i;
1226
1227 if (r->timeout <= NOW)
1228 {
1229 if (!send)
1230 {
1231 send = r;
1232
1233 r->retry++;
1234 r->timeout = NOW + (r->retry * min_latency * conf.dns_timeout_factor);
1235
1236 // the following code changes the query section a bit, forcing
1237 // the forwarder to generate a new request
1238 if (r->stdhdr)
1239 {
1240 //printf ("reencoded header for ID %d retry %d:%d:%d (%p)\n", htons (r->pkt->id), THISNODE->id, r->seqno, r->retry);
1241 //encode_header ((char *)r->pkt->at (6 * 2 + 1), THISNODE->id, r->seqno, r->retry);
1242 }
1243 }
1244 }
1245 else
1246 NEXT (r->timeout);
1247 }
1248
1249 if (!send)
1250 {
1251 // generate a new packet, if wise
1252
1253 if (!established)
1254 {
1255 if (vpn->dns_sndpq.empty ())
1256 {
1257 send = new dns_snd (this);
1258
1259 cfg.reset (THISNODE->id);
1260 send->gen_syn_req ();
1261 }
1262 }
1263 else if (vpn->dns_sndpq.size () < conf.dns_max_outstanding
1264 && !SEQNO_EQ (rcvseq, sndseq - (MAX_WINDOW - 1)))
1265 {
1266 if (last_sent + send_interval <= NOW)
1267 {
1268 //printf ("sending data request etc.\n"); //D
1269 if (!snddq.empty () || last_received + 1. > NOW)
1270 {
1271 poll_interval = send_interval;
1272 NEXT (NOW + send_interval);
1273 }
1274
1275 send = new dns_snd (this);
1276 send->gen_stream_req (sndseq, snddq);
1277 send->timeout = NOW + min_latency * conf.dns_timeout_factor;
1278
1279 sndseq = (sndseq + 1) & SEQNO_MASK;
1280 }
1281 else
1282 NEXT (last_sent + send_interval);
1283 }
1284
1285 if (send)
1286 vpn->dns_sndpq.push_back (send);
1287 }
1288
1289 if (send)
1290 {
1291 last_sent = NOW;
1292 sendto (vpn->dnsv4_fd,
1293 send->pkt->at (0), send->pkt->len, 0,
1294 vpn->dns_forwarder.sav4 (), vpn->dns_forwarder.salenv4 ());
1295 }
1296
1297 slog (L_NOISE, "DNS: pi %f si %f N %f (%d:%d %d)",
1298 poll_interval, send_interval, next - NOW,
1299 vpn->dns_sndpq.size (), snddq.size (),
1300 rcvpq.size ());
1301
1302 // TODO: no idea when this happens, but when next < NOW, we have a problem
1303 // doesn't seem to happen anymore
1304 if (next < NOW + 0.001)
1305 next = NOW + 0.1;
1306
1307 w.start (next);
1308 }
1309
1310 #endif
1311