glitch in the license text detected by hyazinthe, thank you!
[oweals/gnunet.git] / src / dns / gnunet-helper-dns.c
1 /*
2    This file is part of GNUnet.
3    Copyright (C) 2010, 2011, 2012 Christian Grothoff
4
5    GNUnet is free software: you can redistribute it and/or modify it
6    under the terms of the GNU Affero General Public License as published
7    by the Free Software Foundation, either version 3 of the License,
8    or (at your option) any later version.
9
10    GNUnet is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Affero General Public License for more details.
14 */
15
16 /**
17  * @file dns/gnunet-helper-dns.c
18  * @brief helper to install firewall rules to hijack all DNS traffic
19  *        and send it to our virtual interface (except for DNS traffic
20  *        that originates on the specified port).  We then
21  *        allow interacting with our virtual interface via stdin/stdout.
22  * @author Philipp Tölke
23  * @author Christian Grothoff
24  *
25  * This program alters the Linux firewall rules so that DNS traffic
26  * that ordinarily exits the system can be intercepted and managed by
27  * a virtual interface.  In order to achieve this, DNS traffic is
28  * marked with the DNS_MARK given in below and re-routed to a custom
29  * table with the DNS_TABLE ID given below.  Systems and
30  * administrators must take care to not cause conflicts with these
31  * values (it was deemed safest to hardcode them as passing these
32  * values as arguments might permit messing with arbitrary firewall
33  * rules, which would be dangerous).  Traffic coming from the same
34  * group ID as the effective group ID that this process is running
35  * as is not intercepted.
36  *
37  * The code first sets up the virtual interface, then begins to
38  * redirect the DNS traffic to it, and then on errors or SIGTERM shuts
39  * down the virtual interface and removes the rules for the traffic
40  * redirection.
41  *
42  *
43  * Note that having this binary SUID is only partially safe: it will
44  * allow redirecting (and intercepting / mangling) of all DNS traffic
45  * originating from this system by any user who is able to run it.
46  * Furthermore, this code will make it trivial to DoS all DNS traffic
47  * originating from the current system, simply by sending it to
48  * nowhere (redirect stdout to /dev/null).
49  *
50  * Naturally, neither of these problems can be helped as this is the
51  * fundamental purpose of the binary.  Certifying that this code is
52  * "safe" thus only means that it doesn't allow anything else (such
53  * as local priv. escalation, etc.).
54  *
55  * The following list of people have reviewed this code and considered
56  * it safe (within specifications) since the last modification (if you
57  * reviewed it, please have your name added to the list):
58  *
59  * - Christian Grothoff
60  */
61 #include "platform.h"
62
63 #include <linux/if_tun.h>
64
65 /**
66  * Need 'struct GNUNET_MessageHeader'.
67  */
68 #include "gnunet_crypto_lib.h"
69 #include "gnunet_common.h"
70
71 /**
72  * Need DNS message types.
73  */
74 #include "gnunet_protocols.h"
75
76 /**
77  * Maximum size of a GNUnet message (GNUNET_MAX_MESSAGE_SIZE)
78  */
79 #define MAX_SIZE 65536
80
81 #ifndef _LINUX_IN6_H
82 /**
83  * This is in linux/include/net/ipv6.h, but not always exported...
84  */
85 struct in6_ifreq
86 {
87   struct in6_addr ifr6_addr;
88   uint32_t ifr6_prefixlen;
89   unsigned int ifr6_ifindex;
90 };
91 #endif
92
93 /**
94  * Name and full path of IPTABLES binary.
95  */
96 static const char *sbin_iptables;
97
98 /**
99  * Name and full path of IPTABLES binary.
100  */
101 static const char *sbin_ip6tables;
102
103 /**
104  * Name and full path of sysctl binary
105  */
106 static const char *sbin_sysctl;
107
108 /**
109  * Name and full path of IPTABLES binary.
110  */
111 static const char *sbin_ip;
112
113 /**
114  * Port for DNS traffic.
115  */
116 #define DNS_PORT "53"
117
118 /**
119  * Marker we set for our hijacked DNS traffic.  We use GNUnet's
120  * port (2086) plus the DNS port (53) in HEX to make a 32-bit mark
121  * (which is hopefully long enough to not collide); so
122  * 0x08260035 = 136708149 (hopefully unique enough...).
123  */
124 #define DNS_MARK "136708149"
125
126 /**
127  * Table we use for our DNS rules.  0-255 is the range and
128  * 0, 253, 254 and 255 are already reserved.  As this is about
129  * DNS and as "53" is likely (fingers crossed!) high enough to
130  * not usually conflict with a normal user's setup, we use 53
131  * to give a hint that this has something to do with DNS.
132  */
133 #define DNS_TABLE "53"
134
135
136 /**
137  * Control pipe for shutdown via signal. [0] is the read end,
138  * [1] is the write end.
139  */
140 static int cpipe[2];
141
142
143 /**
144  * Signal handler called to initiate "nice" shutdown.  Signals select
145  * loop via non-bocking pipe 'cpipe'.
146  *
147  * @param signal signal number of the signal (not used)
148  */
149 static void
150 signal_handler (int signal)
151 {
152   /* ignore return value, as the signal handler could theoretically
153      be called many times before the shutdown can actually happen */
154   (void) write (cpipe[1], "K", 1);
155 }
156
157
158 /**
159  * Open '/dev/null' and make the result the given
160  * file descriptor.
161  *
162  * @param target_fd desired FD to point to /dev/null
163  * @param flags open flags (O_RDONLY, O_WRONLY)
164  */
165 static void
166 open_dev_null (int target_fd,
167                int flags)
168 {
169   int fd;
170
171   fd = open ("/dev/null", flags);
172   if (-1 == fd)
173     abort ();
174   if (fd == target_fd)
175     return;
176   if (-1 == dup2 (fd, target_fd))
177   {
178     (void) close (fd);
179     abort ();
180   }
181   (void) close (fd);
182 }
183
184
185 /**
186  * Run the given command and wait for it to complete.
187  *
188  * @param file name of the binary to run
189  * @param cmd command line arguments (as given to 'execv')
190  * @return 0 on success, 1 on any error
191  */
192 static int
193 fork_and_exec (const char *file,
194                char *const cmd[])
195 {
196   int status;
197   pid_t pid;
198   pid_t ret;
199
200   pid = fork ();
201   if (-1 == pid)
202   {
203     fprintf (stderr,
204              "fork failed: %s\n",
205              strerror (errno));
206     return 1;
207   }
208   if (0 == pid)
209   {
210     /* we are the child process */
211     /* close stdin/stdout to not cause interference
212        with the helper's main protocol! */
213     (void) close (0);
214     open_dev_null (0, O_RDONLY);
215     (void) close (1);
216     open_dev_null (1, O_WRONLY);
217     (void) execv (file, cmd);
218     /* can only get here on error */
219     fprintf (stderr,
220              "exec `%s' failed: %s\n",
221              file,
222              strerror (errno));
223     _exit (1);
224   }
225   /* keep running waitpid as long as the only error we get is 'EINTR' */
226   while ( (-1 == (ret = waitpid (pid, &status, 0))) &&
227           (errno == EINTR) );
228   if (-1 == ret)
229   {
230     fprintf (stderr,
231              "waitpid failed: %s\n",
232              strerror (errno));
233     return 1;
234   }
235   if (! (WIFEXITED (status) && (0 == WEXITSTATUS (status))))
236     return 1;
237   /* child process completed and returned success, we're happy */
238   return 0;
239 }
240
241
242 /**
243  * Creates a tun-interface called @a dev;
244  *
245  * @param dev is asumed to point to a char[IFNAMSIZ]
246  *        if *dev == '\\0', uses the name supplied by the kernel;
247  * @return the fd to the tun or -1 on error
248  */
249 static int
250 init_tun (char *dev)
251 {
252   struct ifreq ifr;
253   int fd;
254
255   if (NULL == dev)
256   {
257     errno = EINVAL;
258     return -1;
259   }
260
261   if (-1 == (fd = open ("/dev/net/tun", O_RDWR)))
262   {
263     fprintf (stderr, "Error opening `%s': %s\n", "/dev/net/tun",
264              strerror (errno));
265     return -1;
266   }
267
268   if (fd >= FD_SETSIZE)
269   {
270     fprintf (stderr, "File descriptor to large: %d", fd);
271     (void) close (fd);
272     return -1;
273   }
274
275   memset (&ifr, 0, sizeof (ifr));
276   ifr.ifr_flags = IFF_TUN;
277
278   if ('\0' != *dev)
279     strncpy (ifr.ifr_name, dev, IFNAMSIZ);
280
281   if (-1 == ioctl (fd, TUNSETIFF, (void *) &ifr))
282   {
283     fprintf (stderr, "Error with ioctl on `%s': %s\n", "/dev/net/tun",
284              strerror (errno));
285     (void) close (fd);
286     return -1;
287   }
288   strcpy (dev, ifr.ifr_name);
289   return fd;
290 }
291
292
293 /**
294  * @brief Sets the IPv6-Address given in @a address on the interface @a dev
295  *
296  * @param dev the interface to configure
297  * @param address the IPv6-Address
298  * @param prefix_len the length of the network-prefix
299  */
300 static void
301 set_address6 (const char *dev, const char *address, unsigned long prefix_len)
302 {
303   struct ifreq ifr;
304   struct in6_ifreq ifr6;
305   struct sockaddr_in6 sa6;
306   int fd;
307
308   /*
309    * parse the new address
310    */
311   memset (&sa6, 0, sizeof (struct sockaddr_in6));
312   sa6.sin6_family = AF_INET6;
313   if (1 != inet_pton (AF_INET6, address, sa6.sin6_addr.s6_addr))
314   {
315     fprintf (stderr,
316              "Failed to parse IPv6 address `%s': %s\n",
317              address,
318              strerror (errno));
319     exit (1);
320   }
321
322   if (-1 == (fd = socket (PF_INET6, SOCK_DGRAM, 0)))
323   {
324     fprintf (stderr,
325              "Error creating IPv6 socket: %s (ignored)\n",
326              strerror (errno));
327     /* ignore error, maybe only IPv4 works on this system! */
328     return;
329   }
330
331   memset (&ifr, 0, sizeof (struct ifreq));
332   /*
333    * Get the index of the if
334    */
335   strncpy (ifr.ifr_name, dev, IFNAMSIZ);
336   if (-1 == ioctl (fd, SIOGIFINDEX, &ifr))
337   {
338     fprintf (stderr, "ioctl failed at %d: %s\n", __LINE__, strerror (errno));
339     (void) close (fd);
340     exit (1);
341   }
342
343   memset (&ifr6, 0, sizeof (struct in6_ifreq));
344   ifr6.ifr6_addr = sa6.sin6_addr;
345   ifr6.ifr6_ifindex = ifr.ifr_ifindex;
346   ifr6.ifr6_prefixlen = prefix_len;
347
348   /*
349    * Set the address
350    */
351   if (-1 == ioctl (fd, SIOCSIFADDR, &ifr6))
352   {
353     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
354              strerror (errno));
355     (void) close (fd);
356     exit (1);
357   }
358
359   /*
360    * Get the flags
361    */
362   if (-1 == ioctl (fd, SIOCGIFFLAGS, &ifr))
363   {
364     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
365              strerror (errno));
366     (void) close (fd);
367     exit (1);
368   }
369
370   /*
371    * Add the UP and RUNNING flags
372    */
373   ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
374   if (-1 == ioctl (fd, SIOCSIFFLAGS, &ifr))
375   {
376     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
377              strerror (errno));
378     (void) close (fd);
379     exit (1);
380   }
381
382   if (0 != close (fd))
383   {
384     fprintf (stderr, "close failed: %s\n", strerror (errno));
385     exit (1);
386   }
387 }
388
389
390 /**
391  * @brief Sets the IPv4-Address given in @a address on the interface @a dev
392  *
393  * @param dev the interface to configure
394  * @param address the IPv4-Address
395  * @param mask the netmask
396  */
397 static void
398 set_address4 (const char *dev, const char *address, const char *mask)
399 {
400   int fd;
401   struct sockaddr_in *addr;
402   struct ifreq ifr;
403
404   memset (&ifr, 0, sizeof (struct ifreq));
405   addr = (struct sockaddr_in *) &(ifr.ifr_addr);
406   addr->sin_family = AF_INET;
407
408   /*
409    * Parse the address
410    */
411   if (1 != inet_pton (AF_INET, address, &addr->sin_addr.s_addr))
412   {
413     fprintf (stderr,
414              "Failed to parse IPv4 address `%s': %s\n",
415              address,
416              strerror (errno));
417     exit (1);
418   }
419
420   if (-1 == (fd = socket (PF_INET, SOCK_DGRAM, 0)))
421   {
422     fprintf (stderr,
423              "Error creating IPv4 socket: %s\n",
424              strerror (errno));
425     exit (1);
426   }
427
428   strncpy (ifr.ifr_name, dev, IFNAMSIZ);
429
430   /*
431    * Set the address
432    */
433   if (-1 == ioctl (fd, SIOCSIFADDR, &ifr))
434   {
435     fprintf (stderr, "ioctl failed at %d: %s\n", __LINE__, strerror (errno));
436     (void) close (fd);
437     exit (1);
438   }
439
440   /*
441    * Parse the netmask
442    */
443   addr = (struct sockaddr_in *) &(ifr.ifr_netmask);
444   if (1 != inet_pton (AF_INET, mask, &addr->sin_addr.s_addr))
445   {
446     fprintf (stderr, "Failed to parse address `%s': %s\n", mask,
447              strerror (errno));
448     (void) close (fd);
449     exit (1);
450   }
451
452   /*
453    * Set the netmask
454    */
455   if (-1 == ioctl (fd, SIOCSIFNETMASK, &ifr))
456   {
457     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
458              strerror (errno));
459     (void) close (fd);
460     exit (1);
461   }
462
463   /*
464    * Get the flags
465    */
466   if (-1 == ioctl (fd, SIOCGIFFLAGS, &ifr))
467   {
468     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
469              strerror (errno));
470     (void) close (fd);
471     exit (1);
472   }
473
474   /*
475    * Add the UP and RUNNING flags
476    */
477   ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
478   if (-1 == ioctl (fd, SIOCSIFFLAGS, &ifr))
479   {
480     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
481              strerror (errno));
482     (void) close (fd);
483     exit (1);
484   }
485
486   if (0 != close (fd))
487   {
488     fprintf (stderr, "close failed: %s\n", strerror (errno));
489     (void) close (fd);
490     exit (1);
491   }
492 }
493
494
495 /**
496  * Start forwarding to and from the tunnel.  This function runs with
497  * "reduced" priviledges (saved UID is still 0, but effective UID is
498  * the real user ID).
499  *
500  * @param fd_tun tunnel FD
501  */
502 static void
503 run (int fd_tun)
504 {
505   /*
506    * The buffer filled by reading from fd_tun
507    */
508   unsigned char buftun[MAX_SIZE];
509   ssize_t buftun_size = 0;
510   unsigned char *buftun_read = NULL;
511
512   /*
513    * The buffer filled by reading from stdin
514    */
515   unsigned char bufin[MAX_SIZE];
516   ssize_t bufin_size = 0;
517   size_t bufin_rpos = 0;
518   unsigned char *bufin_read = NULL;
519   fd_set fds_w;
520   fd_set fds_r;
521   int max;
522
523   while (1)
524   {
525     FD_ZERO (&fds_w);
526     FD_ZERO (&fds_r);
527
528     /*
529      * We are supposed to read and the buffer is empty
530      * -> select on read from tun
531      */
532     if (0 == buftun_size)
533       FD_SET (fd_tun, &fds_r);
534
535     /*
536      * We are supposed to read and the buffer is not empty
537      * -> select on write to stdout
538      */
539     if (0 < buftun_size)
540       FD_SET (1, &fds_w);
541
542     /*
543      * We are supposed to write and the buffer is empty
544      * -> select on read from stdin
545      */
546     if (NULL == bufin_read)
547       FD_SET (0, &fds_r);
548
549     /*
550      * We are supposed to write and the buffer is not empty
551      * -> select on write to tun
552      */
553     if (NULL != bufin_read)
554       FD_SET (fd_tun, &fds_w);
555
556     FD_SET (cpipe[0], &fds_r);
557     max = (fd_tun > cpipe[0]) ? fd_tun : cpipe[0];
558
559     int r = select (max + 1, &fds_r, &fds_w, NULL, NULL);
560
561     if (-1 == r)
562     {
563       if (EINTR == errno)
564         continue;
565       fprintf (stderr, "select failed: %s\n", strerror (errno));
566       return;
567     }
568
569     if (r > 0)
570     {
571       if (FD_ISSET (cpipe[0], &fds_r))
572         return; /* aborted by signal */
573
574       if (FD_ISSET (fd_tun, &fds_r))
575       {
576         buftun_size =
577             read (fd_tun, buftun + sizeof (struct GNUNET_MessageHeader),
578                   MAX_SIZE - sizeof (struct GNUNET_MessageHeader));
579         if (-1 == buftun_size)
580         {
581           if ( (errno == EINTR) ||
582                (errno == EAGAIN) )
583             {
584               buftun_size = 0;
585               continue;
586             }
587           fprintf (stderr, "read-error: %s\n", strerror (errno));
588           return;
589         }
590         if (0 == buftun_size)
591         {
592           fprintf (stderr, "EOF on tun\n");
593           return;
594         }
595         buftun_read = buftun;
596         {
597           struct GNUNET_MessageHeader *hdr =
598               (struct GNUNET_MessageHeader *) buftun;
599           buftun_size += sizeof (struct GNUNET_MessageHeader);
600           hdr->type = htons (GNUNET_MESSAGE_TYPE_DNS_HELPER);
601           hdr->size = htons (buftun_size);
602         }
603       }
604       else if (FD_ISSET (1, &fds_w))
605       {
606         ssize_t written = write (1, buftun_read, buftun_size);
607
608         if (-1 == written)
609         {
610           if ( (errno == EINTR) ||
611                (errno == EAGAIN) )
612             continue;
613           fprintf (stderr, "write-error to stdout: %s\n", strerror (errno));
614           return;
615         }
616         if (0 == written)
617         {
618           fprintf (stderr, "write returned 0\n");
619           return;
620         }
621         buftun_size -= written;
622         buftun_read += written;
623       }
624
625       if (FD_ISSET (0, &fds_r))
626       {
627         bufin_size = read (0, bufin + bufin_rpos, MAX_SIZE - bufin_rpos);
628         if (-1 == bufin_size)
629         {
630           bufin_read = NULL;
631           if ( (errno == EINTR) ||
632                (errno == EAGAIN) )
633             continue;
634           fprintf (stderr, "read-error: %s\n", strerror (errno));
635           return;
636         }
637         if (0 == bufin_size)
638         {
639           bufin_read = NULL;
640           fprintf (stderr, "EOF on stdin\n");
641           return;
642         }
643         {
644           struct GNUNET_MessageHeader *hdr;
645
646 PROCESS_BUFFER:
647           bufin_rpos += bufin_size;
648           if (bufin_rpos < sizeof (struct GNUNET_MessageHeader))
649             continue;
650           hdr = (struct GNUNET_MessageHeader *) bufin;
651           if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_DNS_HELPER)
652           {
653             fprintf (stderr, "protocol violation!\n");
654             return;
655           }
656           if (ntohs (hdr->size) > bufin_rpos)
657             continue;
658           bufin_read = bufin + sizeof (struct GNUNET_MessageHeader);
659           bufin_size = ntohs (hdr->size) - sizeof (struct GNUNET_MessageHeader);
660           bufin_rpos -= bufin_size + sizeof (struct GNUNET_MessageHeader);
661         }
662       }
663       else if (FD_ISSET (fd_tun, &fds_w))
664       {
665         ssize_t written = write (fd_tun, bufin_read, bufin_size);
666
667         if (-1 == written)
668         {
669           if ( (errno == EINTR) ||
670                (errno == EAGAIN) )
671             continue;
672           fprintf (stderr, "write-error to tun: %s\n", strerror (errno));
673           return;
674         }
675         if (0 == written)
676         {
677           fprintf (stderr, "write returned 0\n");
678           return;
679         }
680         {
681           bufin_size -= written;
682           bufin_read += written;
683           if (0 == bufin_size)
684           {
685             memmove (bufin, bufin_read, bufin_rpos);
686             bufin_read = NULL;  /* start reading again */
687             bufin_size = 0;
688             goto PROCESS_BUFFER;
689           }
690         }
691       }
692     }
693   }
694 }
695
696
697 /**
698  * Main function of "gnunet-helper-dns", which opens a VPN tunnel interface,
699  * redirects all outgoing DNS traffic (except from the specified port) to that
700  * interface and then passes traffic from and to the interface via stdin/stdout.
701  *
702  * Once stdin/stdout close or have other errors, the tunnel is closed and the
703  * DNS traffic redirection is stopped.
704  *
705  * @param argc number of arguments
706  * @param argv 0: binary name (should be "gnunet-helper-vpn")
707  *             1: tunnel interface name (typically "gnunet-dns")
708  *             2: IPv6 address for the tunnel ("FE80::1")
709  *             3: IPv6 netmask length in bits ("64")
710  *             4: IPv4 address for the tunnel ("1.2.3.4")
711  *             5: IPv4 netmask ("255.255.0.0")
712  *             6: skip sysctl, routing and iptables setup ("0")
713  * @return 0 on success, otherwise code indicating type of error:
714  *         1 wrong number of arguments
715  *         2 invalid arguments (i.e. port number / prefix length wrong)
716  *         3 iptables not executable
717  *         4 ip not executable
718  *         5 failed to initialize tunnel interface
719  *         6 failed to initialize control pipe
720  *         8 failed to change routing table, cleanup successful
721  *         9-23 failed to change routing table and failed to undo some changes to routing table
722  *         24 failed to drop privs
723  *         25-39 failed to drop privs and then failed to undo some changes to routing table
724  *         40 failed to regain privs
725  *         41-55 failed to regain prisv and then failed to undo some changes to routing table
726  *         254 insufficient priviledges
727  *         255 failed to handle kill signal properly
728  */
729 int
730 main (int argc, char *const*argv)
731 {
732   int r;
733   char dev[IFNAMSIZ];
734   char mygid[32];
735   int fd_tun;
736   uid_t uid;
737   int nortsetup = 0;
738
739   if (7 != argc)
740   {
741     fprintf (stderr, "Fatal: must supply 6 arguments!\n");
742     return 1;
743   }
744
745   /* assert privs so we can modify the firewall rules! */
746   uid = getuid ();
747 #ifdef HAVE_SETRESUID
748   if (0 != setresuid (uid, 0, 0))
749   {
750     fprintf (stderr, "Failed to setresuid to root: %s\n", strerror (errno));
751     return 254;
752   }
753 #else
754   if (0 != seteuid (0))
755   {
756     fprintf (stderr, "Failed to seteuid back to root: %s\n", strerror (errno));
757     return 254;
758   }
759 #endif
760   if (0 == strncmp (argv[6], "1", 2))
761     nortsetup = 1;
762
763   if (0 == nortsetup)
764   {
765     /* verify that the binaries we care about are executable */
766     if (0 == access ("/sbin/iptables", X_OK))
767       sbin_iptables = "/sbin/iptables";
768     else if (0 == access ("/usr/sbin/iptables", X_OK))
769       sbin_iptables = "/usr/sbin/iptables";
770     else
771     {
772       fprintf (stderr,
773                "Fatal: executable iptables not found in approved directories: %s\n",
774                strerror (errno));
775       return 3;
776     }
777     if (0 == access ("/sbin/ip6tables", X_OK))
778       sbin_ip6tables = "/sbin/ip6tables";
779     else if (0 == access ("/usr/sbin/ip6tables", X_OK))
780       sbin_ip6tables = "/usr/sbin/ip6tables";
781     else
782     {
783       fprintf (stderr,
784                "Fatal: executable ip6tables not found in approved directories: %s\n",
785                strerror (errno));
786       return 3;
787     }
788     if (0 == access ("/sbin/ip", X_OK))
789       sbin_ip = "/sbin/ip";
790     else if (0 == access ("/usr/sbin/ip", X_OK))
791       sbin_ip = "/usr/sbin/ip";
792     else if (0 == access ("/bin/ip", X_OK)) /* gentoo has it there */
793       sbin_ip = "/bin/ip";
794     else
795     {
796       fprintf (stderr,
797                "Fatal: executable ip not found in approved directories: %s\n",
798                strerror (errno));
799       return 4;
800     }
801     if (0 == access ("/sbin/sysctl", X_OK))
802       sbin_sysctl = "/sbin/sysctl";
803     else if (0 == access ("/usr/sbin/sysctl", X_OK))
804       sbin_sysctl = "/usr/sbin/sysctl";
805     else
806     {
807       fprintf (stderr,
808                "Fatal: executable sysctl not found in approved directories: %s\n",
809                strerror (errno));
810       return 5;
811     }
812   }
813
814   /* setup 'mygid' string */
815   snprintf (mygid, sizeof (mygid), "%d", (int) getegid());
816
817   /* do not die on SIGPIPE */
818   if (SIG_ERR == signal (SIGPIPE, SIG_IGN))
819   {
820     fprintf (stderr, "Failed to protect against SIGPIPE: %s\n",
821              strerror (errno));
822     return 7;
823   }
824
825   /* setup pipe to shutdown nicely on SIGINT */
826   if (0 != pipe (cpipe))
827   {
828     fprintf (stderr,
829              "Fatal: could not setup control pipe: %s\n",
830              strerror (errno));
831     return 6;
832   }
833   if (cpipe[0] >= FD_SETSIZE)
834   {
835     fprintf (stderr, "Pipe file descriptor to large: %d", cpipe[0]);
836     (void) close (cpipe[0]);
837     (void) close (cpipe[1]);
838     return 6;
839   }
840   {
841     /* make pipe non-blocking, as we theoretically could otherwise block
842        in the signal handler */
843     int flags = fcntl (cpipe[1], F_GETFL);
844     if (-1 == flags)
845     {
846       fprintf (stderr, "Failed to read flags for pipe: %s", strerror (errno));
847       (void) close (cpipe[0]);
848       (void) close (cpipe[1]);
849       return 6;
850     }
851     flags |= O_NONBLOCK;
852     if (0 != fcntl (cpipe[1], F_SETFL, flags))
853     {
854       fprintf (stderr, "Failed to make pipe non-blocking: %s", strerror (errno));
855       (void) close (cpipe[0]);
856       (void) close (cpipe[1]);
857       return 6;
858     }
859   }
860   if ( (SIG_ERR == signal (SIGTERM, &signal_handler)) ||
861 #if (SIGTERM != GNUNET_TERM_SIG)
862        (SIG_ERR == signal (GNUNET_TERM_SIG, &signal_handler)) ||
863 #endif
864        (SIG_ERR == signal (SIGINT, &signal_handler)) ||
865        (SIG_ERR == signal (SIGHUP, &signal_handler)) )
866   {
867     fprintf (stderr,
868              "Fatal: could not initialize signal handler: %s\n",
869              strerror (errno));
870     (void) close (cpipe[0]);
871     (void) close (cpipe[1]);
872     return 7;
873   }
874
875
876   /* get interface name */
877   strncpy (dev, argv[1], IFNAMSIZ);
878   dev[IFNAMSIZ - 1] = '\0';
879
880   /* Disable rp filtering */
881   if (0 == nortsetup)
882   {
883     char *const sysctl_args[] = {"sysctl", "-w",
884       "net.ipv4.conf.all.rp_filter=0", NULL};
885     char *const sysctl_args2[] = {"sysctl", "-w",
886       "net.ipv4.conf.default.rp_filter=0", NULL};
887     if ((0 != fork_and_exec (sbin_sysctl, sysctl_args)) ||
888         (0 != fork_and_exec (sbin_sysctl, sysctl_args2)))
889     {
890       fprintf (stderr,
891                "Failed to disable rp filtering.\n");
892       return 5;
893     }
894   }
895
896
897   /* now open virtual interface (first part that requires root) */
898   if (-1 == (fd_tun = init_tun (dev)))
899   {
900     fprintf (stderr, "Fatal: could not initialize tun-interface\n");
901     (void) signal (SIGTERM, SIG_IGN);
902 #if (SIGTERM != GNUNET_TERM_SIG)
903     (void) signal (GNUNET_TERM_SIG, SIG_IGN);
904 #endif
905     (void) signal (SIGINT, SIG_IGN);
906     (void) signal (SIGHUP, SIG_IGN);
907     (void) close (cpipe[0]);
908     (void) close (cpipe[1]);
909     return 5;
910   }
911
912   /* now set interface addresses */
913   {
914     const char *address = argv[2];
915     long prefix_len = atol (argv[3]);
916
917     if ((prefix_len < 1) || (prefix_len > 127))
918     {
919       fprintf (stderr, "Fatal: prefix_len out of range\n");
920       (void) signal (SIGTERM, SIG_IGN);
921 #if (SIGTERM != GNUNET_TERM_SIG)
922     (void) signal (GNUNET_TERM_SIG, SIG_IGN);
923 #endif
924       (void) signal (SIGINT, SIG_IGN);
925       (void) signal (SIGHUP, SIG_IGN);
926       (void) close (cpipe[0]);
927       (void) close (cpipe[1]);
928       return 2;
929     }
930     set_address6 (dev, address, prefix_len);
931   }
932
933   {
934     const char *address = argv[4];
935     const char *mask = argv[5];
936
937     set_address4 (dev, address, mask);
938   }
939
940
941   /* update routing tables -- next part why we need SUID! */
942   /* Forward everything from our EGID (which should only be held
943      by the 'gnunet-service-dns') and with destination
944      to port 53 on UDP, without hijacking */
945   if (0 == nortsetup)
946   {
947     r = 8; /* failed to fully setup routing table */
948     {
949       char *const mangle_args[] =
950         {
951          "iptables", "-m", "owner", "-t", "mangle", "-I", "OUTPUT", "1", "-p",
952          "udp", "--gid-owner", mygid, "--dport", DNS_PORT, "-j",
953          "ACCEPT", NULL
954         };
955       if (0 != fork_and_exec (sbin_iptables, mangle_args))
956         goto cleanup_rest;
957     }
958     {
959       char *const mangle_args[] =
960         {
961          "ip6tables", "-m", "owner", "-t", "mangle", "-I", "OUTPUT", "1", "-p",
962          "udp", "--gid-owner", mygid, "--dport", DNS_PORT, "-j",
963          "ACCEPT", NULL
964         };
965       if (0 != fork_and_exec (sbin_ip6tables, mangle_args))
966         goto cleanup_mangle_1b;
967     }
968     /* Mark all of the other DNS traffic using our mark DNS_MARK,
969        unless it is on a link-local IPv6 address, which we cannot support. */
970     {
971       char *const mark_args[] =
972         {
973          "iptables", "-t", "mangle", "-I", "OUTPUT", "2", "-p",
974          "udp", "--dport", DNS_PORT,
975          "-j", "MARK", "--set-mark", DNS_MARK,
976          NULL
977         };
978       if (0 != fork_and_exec (sbin_iptables, mark_args))
979         goto cleanup_mangle_1;
980     }
981     {
982       char *const mark_args[] =
983         {
984          "ip6tables", "-t", "mangle", "-I", "OUTPUT", "2", "-p",
985          "udp", "--dport", DNS_PORT,
986          "!", "-s", "fe80::/10", /* this line excludes link-local traffic */
987          "-j", "MARK", "--set-mark", DNS_MARK,
988          NULL
989         };
990       if (0 != fork_and_exec (sbin_ip6tables, mark_args))
991         goto cleanup_mark_2b;
992     }
993     /* Forward all marked DNS traffic to our DNS_TABLE */
994     {
995       char *const forward_args[] =
996         {
997          "ip", "rule", "add", "fwmark", DNS_MARK, "table", DNS_TABLE, NULL
998         };
999       if (0 != fork_and_exec (sbin_ip, forward_args))
1000         goto cleanup_mark_2;
1001     }
1002     {
1003       char *const forward_args[] =
1004         {
1005           "ip", "-6", "rule", "add", "fwmark", DNS_MARK, "table", DNS_TABLE, NULL
1006         };
1007       if (0 != fork_and_exec (sbin_ip, forward_args))
1008         goto cleanup_forward_3b;
1009     }
1010     /* Finally, add rule in our forwarding table to pass to our virtual interface */
1011     {
1012       char *const route_args[] =
1013         {
1014          "ip", "route", "add", "default", "dev", dev,
1015          "table", DNS_TABLE, NULL
1016         };
1017       if (0 != fork_and_exec (sbin_ip, route_args))
1018         goto cleanup_forward_3;
1019     }
1020     {
1021       char *const route_args[] =
1022         {
1023           "ip", "-6", "route", "add", "default", "dev", dev,
1024           "table", DNS_TABLE, NULL
1025         };
1026       if (0 != fork_and_exec (sbin_ip, route_args))
1027         goto cleanup_route_4b;
1028     }
1029   }
1030
1031   /* drop privs *except* for the saved UID; this is not perfect, but better
1032      than doing nothing */
1033 #ifdef HAVE_SETRESUID
1034   if (0 != setresuid (uid, uid, 0))
1035   {
1036     fprintf (stderr, "Failed to setresuid: %s\n", strerror (errno));
1037     r = 24;
1038     goto cleanup_route_4;
1039   }
1040 #else
1041   /* Note: no 'setuid' here as we must keep our saved UID as root */
1042   if (0 != seteuid (uid))
1043   {
1044     fprintf (stderr, "Failed to seteuid: %s\n", strerror (errno));
1045     r = 24;
1046     goto cleanup_route_4;
1047   }
1048 #endif
1049
1050   r = 0; /* did fully setup routing table (if nothing else happens, we were successful!) */
1051
1052   /* now forward until we hit a problem */
1053   run (fd_tun);
1054
1055   /* now need to regain privs so we can remove the firewall rules we added! */
1056 #ifdef HAVE_SETRESUID
1057   if (0 != setresuid (uid, 0, 0))
1058   {
1059     fprintf (stderr, "Failed to setresuid back to root: %s\n", strerror (errno));
1060     r = 40;
1061     goto cleanup_route_4;
1062   }
1063 #else
1064   if (0 != seteuid (0))
1065   {
1066     fprintf (stderr, "Failed to seteuid back to root: %s\n", strerror (errno));
1067     r = 40;
1068     goto cleanup_route_4;
1069   }
1070 #endif
1071
1072   /* update routing tables again -- this is why we could not fully drop privs */
1073   /* now undo updating of routing tables; normal exit or clean-up-on-error case */
1074  cleanup_route_4:
1075   if (0 == nortsetup)
1076   {
1077     char *const route_clean_args[] =
1078       {
1079         "ip", "-6", "route", "del", "default", "dev", dev,
1080         "table", DNS_TABLE, NULL
1081       };
1082     if (0 != fork_and_exec (sbin_ip, route_clean_args))
1083       r += 1;
1084   }
1085  cleanup_route_4b:
1086   if (0 == nortsetup)
1087   {
1088     char *const route_clean_args[] =
1089       {
1090         "ip", "route", "del", "default", "dev", dev,
1091         "table", DNS_TABLE, NULL
1092       };
1093     if (0 != fork_and_exec (sbin_ip, route_clean_args))
1094       r += 1;
1095   }
1096  cleanup_forward_3:
1097   if (0 == nortsetup)
1098   {
1099     char *const forward_clean_args[] =
1100       {
1101         "ip", "-6", "rule", "del", "fwmark", DNS_MARK, "table", DNS_TABLE, NULL
1102       };
1103     if (0 != fork_and_exec (sbin_ip, forward_clean_args))
1104       r += 2;
1105   }
1106  cleanup_forward_3b:
1107   if (0 == nortsetup)
1108   {
1109     char *const forward_clean_args[] =
1110       {
1111         "ip", "rule", "del", "fwmark", DNS_MARK, "table", DNS_TABLE, NULL
1112       };
1113     if (0 != fork_and_exec (sbin_ip, forward_clean_args))
1114       r += 2;
1115   }
1116  cleanup_mark_2:
1117   if (0 == nortsetup)
1118   {
1119     char *const mark_clean_args[] =
1120       {
1121         "ip6tables", "-t", "mangle", "-D", "OUTPUT", "-p", "udp",
1122         "--dport", DNS_PORT,
1123         "!", "-s", "fe80::/10", /* this line excludes link-local traffic */
1124         "-j", "MARK", "--set-mark", DNS_MARK, NULL
1125       };
1126     if (0 != fork_and_exec (sbin_ip6tables, mark_clean_args))
1127       r += 4;
1128   }
1129  cleanup_mark_2b:
1130   if (0 == nortsetup)
1131   {
1132     char *const mark_clean_args[] =
1133       {
1134         "iptables", "-t", "mangle", "-D", "OUTPUT", "-p", "udp",
1135         "--dport", DNS_PORT, "-j", "MARK", "--set-mark", DNS_MARK, NULL
1136       };
1137     if (0 != fork_and_exec (sbin_iptables, mark_clean_args))
1138       r += 4;
1139   }
1140  cleanup_mangle_1:
1141   if (0 == nortsetup)
1142   {
1143     char *const mangle_clean_args[] =
1144       {
1145         "ip6tables", "-m", "owner", "-t", "mangle", "-D", "OUTPUT", "-p", "udp",
1146          "--gid-owner", mygid, "--dport", DNS_PORT, "-j", "ACCEPT",
1147         NULL
1148       };
1149     if (0 != fork_and_exec (sbin_ip6tables, mangle_clean_args))
1150       r += 8;
1151   }
1152  cleanup_mangle_1b:
1153   if (0 == nortsetup)
1154   {
1155     char *const mangle_clean_args[] =
1156       {
1157         "iptables", "-m", "owner", "-t", "mangle", "-D", "OUTPUT", "-p", "udp",
1158          "--gid-owner", mygid, "--dport", DNS_PORT, "-j", "ACCEPT",
1159         NULL
1160       };
1161     if (0 != fork_and_exec (sbin_iptables, mangle_clean_args))
1162       r += 8;
1163   }
1164
1165  cleanup_rest:
1166   /* close virtual interface */
1167   (void) close (fd_tun);
1168   /* remove signal handler so we can close the pipes */
1169   (void) signal (SIGTERM, SIG_IGN);
1170 #if (SIGTERM != GNUNET_TERM_SIG)
1171     (void) signal (GNUNET_TERM_SIG, SIG_IGN);
1172 #endif
1173   (void) signal (SIGINT, SIG_IGN);
1174   (void) signal (SIGHUP, SIG_IGN);
1175   (void) close (cpipe[0]);
1176   (void) close (cpipe[1]);
1177   return r;
1178 }
1179
1180 /* end of gnunet-helper-dns.c */