1 #include <signal.h>
2 #include <poll.h>
3 #include <unistd.h>
4 #include "env.h"
5 #include "byte.h"
6 #include "xsocket.h"
7 #include "strtoip.h"
8 #include "randombytes.h"
9 #include "crypto_uint64.h"
10 #include "query.h"
11 #include "die.h"
12 #include "warn.h"
13 #include "e.h"
14 #include "numtostr.h"
15 #include "strtonum.h"
16 #include "cache.h"
17 #include "response.h"
18 #include "log.h"
19 #include "roots.h"
20 #include "hexparse.h"
21 #include "alloc.h"
22 #include "milliseconds.h"
23 #include "blocking.h"
24 #include "uint16_pack_big.h"
25 #include "uint16_unpack_big.h"
26 #include "portparse.h"
27 #include "droproot.h"
28 #include "okclient.h"
29 #include "purge.h"
30 
31 static int flagokclient = 0;
32 
packetquery(unsigned char * buf,long long len,unsigned char ** q,unsigned char qtype[2],unsigned char qclass[2],unsigned char id[2])33 static int packetquery(unsigned char *buf, long long len, unsigned char **q, unsigned char qtype[2], unsigned char qclass[2], unsigned char id[2]) {
34 
35     long long pos;
36     unsigned char header[12];
37 
38     errno = EPROTO;
39     pos = dns_packet_copy(buf, len, 0, header, 12); if (!pos) return 0;
40     if (header[2] & 128) return 0; /* must not respond to responses */
41     if (!(header[2] & 1)) return 0; /* do not respond to non-recursive queries */
42     if (header[2] & 120) return 0;
43     if (header[2] & 2) return 0;
44     if (!byte_isequal(header + 4, 2, "\0\1")) return 0;
45 
46     pos = dns_packet_getname(buf, len, pos, q); if (!pos) return 0;
47     pos = dns_packet_copy(buf, len, pos, qtype, 2); if (!pos) return 0;
48     pos = dns_packet_copy(buf, len, pos, qclass, 2); if (!pos) return 0;
49     if (!byte_isequal(qclass, 2, DNS_C_IN) && !byte_isequal(qclass, 2, DNS_C_ANY)) return 0;
50 
51     byte_copy(id, 2, header);
52     return 1;
53 }
54 
55 static unsigned char myport[2] = {0, 53};
56 static unsigned char myipoutgoing[32];
57 static unsigned char myipincoming[16];
58 static int mytypeincoming = XSOCKET_V6;
59 
60 static unsigned char buf[1024];
61 crypto_uint64 numqueries = 0;
62 
63 
64 static int udp53;
65 
66 #define MAXUDPDUPLICATED 10
67 #define MAXUDP 200
68 static struct udpclient {
69     struct query q;
70     long long start;
71     crypto_uint64 active; /* query number, if active; otherwise 0 */
72     struct pollfd *io;
73     unsigned char ip[16];
74     unsigned char port[2];
75     long long scope_id;
76     unsigned char id[2];
77 } u[MAXUDP];
78 long long uactive = 0;
79 
u_drop(long long j)80 static void u_drop(long long j) {
81     if (!u[j].active) return;
82     log_querydrop(&u[j].active);
83     u[j].active = 0; --uactive;
84 }
85 
u_respond(long long j)86 static void u_respond(long long j) {
87 
88     if (!u[j].active) return;
89     response_id(u[j].id);
90     if (response_len > 512) response_tc();
91     xsocket_send(udp53, mytypeincoming, response, response_len, u[j].ip, u[j].port, u[j].scope_id);
92     log_querydone(&u[j].active, response_len);
93     u[j].active = 0; --uactive;
94 }
95 
96 
u_duplicatequerycount(unsigned char * q,unsigned char * qtype)97 static long long u_duplicatequerycount(unsigned char *q, unsigned char *qtype) {
98 
99     long long j, c = 0;
100     struct query *z;
101 
102     for (j = 0; j < MAXUDP; ++j) {
103         if (!u[j].active) continue;
104         z = &u[j].q;
105         if (!byte_isequal(z->type, 2, qtype)) continue;
106         if (!dns_domain_equal(z->name[0], q)) continue;
107         ++c;
108     }
109     return c;
110 }
111 
u_new(void)112 static void u_new(void) {
113 
114     long long j;
115     long long i;
116     struct udpclient *x;
117     long long len;
118     static unsigned char *q = 0;
119     unsigned char qtype[2];
120     unsigned char qclass[2];
121     crypto_uint16 port;
122 
123     for (j = 0; j < MAXUDP; ++j)
124         if (!u[j].active)
125             break;
126 
127     if (j >= MAXUDP) {
128         j = 0;
129         for (i = 1;i < MAXUDP;++i)
130             if (u[i].start < u[j].start)
131                 j = i;
132         errno = ETIMEDOUT;
133         u_drop(j);
134     }
135 
136     x = u + j;
137     x->start = milliseconds();
138 
139     len = xsocket_recv(udp53, mytypeincoming, buf, sizeof buf, x->ip, x->port, &x->scope_id);
140     if (len == -1) return;
141     if (len >= sizeof buf) return;
142     port = uint16_unpack_big(x->port);
143     if (port < 1024) if (port != 53) return;
144 
145     if (!flagokclient && !okclient(x->ip)) { log_queryreject(x->ip, x->port, 0, 0, 0, "IP address not allowed"); return; }
146 
147     if (!packetquery(buf, len, &q, qtype, qclass, x->id)) { log_queryreject(x->ip, x->port, x->id, q, qtype, "bad query"); return; }
148     if (u_duplicatequerycount(q, qtype) >= MAXUDPDUPLICATED) { log_queryreject(x->ip, x->port, x->id, q, qtype, "too many duplicate queries"); return; }
149 
150     x->active = ++numqueries; ++uactive;
151     log_query(&x->active, x->ip, x->port, x->id, q, qtype);
152     switch(query_start(&x->q, q, qtype, qclass, myipoutgoing)) {
153         case -1:
154             u_drop(j);
155             return;
156         case 1:
157             u_respond(j);
158     }
159 }
160 
161 
162 static int tcp53;
163 
164 #define MAXTCP 20
165 struct tcpclient {
166     struct query q;
167     long long start;
168     long long timeout;
169     crypto_uint64 active; /* query number or 1, if active; otherwise 0 */
170     struct pollfd *io;
171     unsigned char ip[16]; /* send response to this address */
172     unsigned char port[2]; /* send response to this port */
173     long long scope_id;
174     int type;
175     unsigned char id[2];
176     int tcp; /* open TCP socket, if active */
177     int state;
178     unsigned char *buf; /* 0, or dynamically allocated of length len */
179     long long len;
180     long long pos;
181 } t[MAXTCP];
182 long long tactive = 0;
183 
184 /*
185 state 1: buf 0; normal state at beginning of TCP connection
186 state 2: buf 0; have read 1 byte of query packet length into len
187 state 3: buf allocated; have read pos bytes of buf
188 state 0: buf 0; handling query in q
189 state -1: buf allocated; have written pos bytes
190 */
191 
t_free(long long j)192 static void t_free(long long j) {
193     if (!t[j].buf) return;
194     alloc_free(t[j].buf);
195     t[j].buf = 0;
196 }
197 
t_timeout(long long j)198 static void t_timeout(long long j) {
199 
200     if (!t[j].active) return;
201     t[j].timeout = milliseconds() + 10000;
202 }
203 
t_close(long long j)204 static void t_close(long long j) {
205     if (!t[j].active) return;
206     t_free(j);
207     log_tcpclose(t[j].ip, t[j].port);
208     close(t[j].tcp);
209     t[j].active = 0; --tactive;
210 }
211 
t_drop(long long j)212 static void t_drop(long long j) {
213     log_querydrop(&t[j].active);
214     errno = EPIPE;
215     t_close(j);
216 }
217 
t_respond(long long j)218 static void t_respond(long long j) {
219     if (!t[j].active) return;
220     log_querydone(&t[j].active, response_len);
221     response_id(t[j].id);
222     t[j].len = response_len + 2;
223     t_free(j);
224     t[j].buf = alloc(response_len + 2);
225     if (!t[j].buf) { t_close(j); return; }
226     uint16_pack_big(t[j].buf, response_len);
227     byte_copy(t[j].buf + 2, response_len, response);
228     t[j].pos = 0;
229     t[j].state = -1;
230 }
231 
t_rw(long long j)232 static void t_rw(long long j) {
233 
234     struct tcpclient *x;
235     unsigned char ch;
236     static unsigned char *q = 0;
237     unsigned char qtype[2];
238     unsigned char qclass[2];
239     long long r;
240 
241     x = t + j;
242     if (x->state == -1) {
243         r = write(x->tcp, x->buf + x->pos, x->len - x->pos);
244         if (r <= 0) { t_close(j); return; }
245         x->pos += r;
246         if (x->pos == x->len) {
247             t_free(j);
248             x->state = 1; /* could drop connection immediately */
249         }
250         return;
251     }
252 
253     if (x->state == 1) {
254         r = read(x->tcp, &ch, 1);
255         if (r == 0) { errno = EPIPE; t_close(j); return; }
256         if (r < 0) { t_close(j); return; }
257         x->len = (unsigned char) ch;
258         x->len <<= 8;
259         x->state = 2;
260         return;
261     }
262     if (x->state == 2) {
263         r = read(x->tcp, &ch, 1);
264         if (r == 0) { errno = EPIPE; t_close(j); return; }
265         if (r < 0) { t_close(j); return; }
266         x->len += (unsigned char) ch;
267         if (!x->len) { errno = EPROTO; t_close(j); return; }
268         x->buf = alloc(x->len);
269         if (!x->buf) { t_close(j); return; }
270         x->pos = 0;
271         x->state = 3;
272         return;
273     }
274 
275     if (x->state != 3) return; /* impossible */
276 
277     r = read(x->tcp, x->buf + x->pos, x->len - x->pos);
278     if (r == 0) { errno = EPIPE; t_close(j); return; }
279     if (r < 0) { t_close(j); return; }
280     x->pos += r;
281     if (x->pos < x->len) return;
282 
283     if (!packetquery(x->buf, x->len, &q, qtype, qclass, x->id)) { log_queryreject(x->ip, x->port, x->id, q, qtype, "bad query"); t_close(j); return; }
284 
285     x->active = ++numqueries;
286     log_query(&x->active, x->ip, x->port, x->id, q, qtype);
287     switch(query_start(&x->q,q,qtype,qclass,myipoutgoing)) {
288         case -1:
289             t_drop(j);
290             return;
291         case 1:
292             t_respond(j);
293             return;
294     }
295     t_free(j);
296     x->state = 0;
297 }
298 
t_new(void)299 static void t_new(void) {
300 
301     long long i;
302     long long j;
303     struct tcpclient *x;
304     crypto_uint16 port;
305 
306     for (j = 0;j < MAXTCP;++j)
307         if (!t[j].active)
308             break;
309 
310     if (j >= MAXTCP) {
311         j = 0;
312         for (i = 1;i < MAXTCP;++i)
313             if (t[i].start < t[j].start)
314                 j = i;
315         errno = ETIMEDOUT;
316         if (t[j].state == 0)
317             t_drop(j);
318         else
319             t_close(j);
320     }
321 
322     x = t + j;
323     x->start = milliseconds();
324 
325     x->tcp = xsocket_accept(tcp53, mytypeincoming, x->ip, x->port, &x->scope_id);
326     if (x->tcp == -1) return;
327     port = uint16_unpack_big(x->port);
328     if (port < 1024) if (port != 53) { close(x->tcp); return; }
329     if (!flagokclient && !okclient(x->ip)) { log_queryreject(x->ip, x->port, 0, 0, 0, "IP address not allowed"); close(x->tcp); return; }
330     blocking_disable(x->tcp);
331 
332     x->active = 1; ++tactive;
333     x->state = 1;
334     t_timeout(j);
335 
336     log_tcpopen(x->ip,x->port);
337 }
338 
339 static struct pollfd io[3 + MAXUDP + MAXTCP];
340 static struct pollfd *udp53io;
341 static struct pollfd *tcp53io;
342 
doit(void)343 static void doit(void) {
344 
345     long long j;
346     long long deadline;
347     long long stamp;
348     long long timeout;
349     long long iolen;
350     int r;
351 
352   for (;;) {
353     stamp = milliseconds();
354     deadline = stamp + 120000;
355 
356     iolen = 0;
357 
358     udp53io = io + iolen++;
359     udp53io->fd = udp53;
360     udp53io->events = POLLIN;
361 
362     tcp53io = io + iolen++;
363     tcp53io->fd = tcp53;
364     tcp53io->events = POLLIN;
365 
366     for (j = 0;j < MAXUDP;++j)
367       if (u[j].active) {
368         u[j].io = io + iolen++;
369         query_io(&u[j].q,u[j].io,&deadline);
370       }
371     for (j = 0;j < MAXTCP;++j)
372       if (t[j].active) {
373         t[j].io = io + iolen++;
374         if (t[j].state == 0)
375           query_io(&t[j].q,t[j].io,&deadline);
376         else {
377           if (t[j].timeout < deadline) deadline = t[j].timeout;
378           t[j].io->fd = t[j].tcp;
379           t[j].io->events = (t[j].state > 0) ? POLLIN : POLLOUT;
380         }
381       }
382 
383       timeout = deadline - stamp;
384       if (timeout < 0) timeout = 10;
385       poll(io, iolen, timeout);
386 
387     for (j = 0;j < MAXUDP;++j)
388       if (u[j].active) {
389         r = query_get(&u[j].q,u[j].io,stamp);
390         if (r == -1) u_drop(j);
391         if (r == 1) u_respond(j);
392       }
393 
394     for (j = 0;j < MAXTCP;++j)
395       if (t[j].active) {
396         if (t[j].io->revents)
397           t_timeout(j);
398         if (t[j].state == 0) {
399           r = query_get(&t[j].q,t[j].io,stamp);
400           if (r == -1) t_drop(j);
401           if (r == 1) t_respond(j);
402         }
403         else
404           if (t[j].io->revents || (t[j].timeout < stamp))
405             t_rw(j);
406       }
407 
408     if (udp53io)
409       if (udp53io->revents)
410         u_new();
411 
412     if (tcp53io)
413       if (tcp53io->revents)
414         t_new();
415   }
416 }
417 
418 
419 static unsigned char skseed[32];
420 static unsigned char sk[32 + 16];
421 
422 #define FATAL "dqcache: fatal: "
423 #define WARNING "dqcache: warning: "
424 
425 
removesecrets(void)426 static void removesecrets(void) {
427 
428     query_purge();
429     dns_nonce_purge();
430     purge(skseed, sizeof skseed);
431     purge(sk, sizeof sk);
432 }
433 
die_fatal(const char * trouble,const char * fn)434 static void die_fatal(const char *trouble, const char *fn) {
435 
436     removesecrets();
437     if (errno) {
438         if (fn) die_7(111, FATAL, trouble, " ", fn, ": ", e_str(errno), "\n");
439         die_5(111, FATAL, trouble, ": ", e_str(errno), "\n");
440     }
441     if (fn) die_5(111, FATAL, trouble, " ", fn, "\n");
442     die_3(111, FATAL, trouble, "\n");
443 }
444 
445 
446 static char *dnscurvetype = 0;
447 
reload(int sig)448 static void reload(int sig) {
449     if (!roots_init(dnscurvetype)) die_fatal("unable to read servers", 0);
450 }
dump(int sig)451 static void dump(int sig){
452     if (cache_dump() == -1) warn_4(WARNING, "unable to dump cache: ", e_str(errno), "\n");
453 }
454 
exitasap(int sig)455 static void exitasap(int sig){
456     removesecrets();
457     dump(0);
458     die_0(0);
459 }
460 
clean(int sig)461 static void clean(int sig){
462     cache_clean();
463 }
464 
465 
main(int argc,char ** argv)466 int main(int argc, char **argv) {
467 
468     long long cachesize, ll;
469     unsigned char port[2];
470     char *x;
471 
472     signal(SIGPIPE, SIG_IGN);
473     signal(SIGHUP,  reload);
474     signal(SIGALRM, dump);
475     signal(SIGINT, clean);
476     signal(SIGTERM, exitasap);
477 
478     if (!strtoip(myipincoming, env_get("IP"))) {
479         byte_copy(myipincoming, 16, xsocket_ANYIP);
480     }
481     mytypeincoming = xsocket_type(myipincoming);
482 
483     udp53 = xsocket_udp(mytypeincoming);
484     if (udp53 == -1) die_fatal("unable to create UDP socket", 0);
485     if (xsocket_bind_reuse(udp53, mytypeincoming, myipincoming, myport, 0) == -1) die_fatal("unable to bind UDP socket", 0);
486 
487     tcp53 = xsocket_tcp(mytypeincoming);
488     if (tcp53 == -1) die_fatal("unable to create TCP socket", 0);
489     if (xsocket_bind_reuse(tcp53, mytypeincoming, myipincoming, myport, 0) == -1) die_fatal("unable to bind TCP socket", 0);
490 
491     randombytes(skseed, sizeof skseed);
492     x = env_get("SECRETKEY");
493     if (x) {
494         if (!hexparse(skseed, sizeof skseed, x)) {
495             warn_2(WARNING, "unable to parse $SECRETKEY\n");
496             randombytes(skseed, sizeof skseed);
497         }
498         while (*x) { *x = 0; ++x; }
499     }
500 
501     droproot(FATAL);
502 
503     dns_keys_derive(sk, sizeof sk, skseed);
504     query_init(sk);
505 
506     x = env_get("NONCESTART");
507     if (!dns_nonce_init(x, sk + 32)) die_fatal("too long $NONCESTART", x);
508 
509     purge(skseed, sizeof skseed);
510     purge(sk, sizeof sk);
511 
512     dns_transmit_magic(env_get("QUERYMAGIC"), env_get("RESPONSEMAGIC"));
513 
514     xsocket_tryreservein(udp53, 131072);
515 
516     if (!strtoip(myipoutgoing, env_get("IPSEND4"))) {
517         byte_copy(myipoutgoing, 16, xsocket_ANYIP4);
518     }
519     if (!strtoip(myipoutgoing + 16, env_get("IPSEND6"))) {
520         byte_copy(myipoutgoing + 16, 16, xsocket_ANYIP6);
521     }
522     if (portparse(port, env_get("REMOTEPORT"))) {
523         query_remoteport(port);
524     }
525 
526     if (!strtonum(&cachesize, env_get("CACHESIZE"))) {
527         cachesize = 10000000;
528     }
529     if (!cache_init(cachesize)) die_fatal("not enough memory for cache of size", numtostr(0, cachesize));
530 
531     if (env_get("HIDETTL")) response_hidettl();
532     if (env_get("FORWARDONLY")) query_forwardonly();
533     if (env_get("TCPONLY")) query_tcponly();
534     if (env_get("DISABLEIPV6")) query_ipv4only();
535     if (strtonum(&ll, env_get("MINTTL"))) query_minttl(ll);
536     if (env_get("OKCLIENT")) flagokclient = 1;
537 
538     dnscurvetype = env_get("DNSCURVETYPE");
539     query_dnscurvetype(dnscurvetype);
540     if (!roots_init(dnscurvetype)) die_fatal("unable to read servers", 0);
541 
542     if (xsocket_listen(tcp53, 20) == -1) die_fatal("unable to listen on TCP socket", 0);
543 
544     if (cache_load() == -1) warn_4(WARNING, "unable to load cache: ", e_str(errno), "\n");
545 
546     log_startup();
547     doit();
548 
549     return 111;
550 }
551