2 This file is part of GNUnet.
3 (C) 2010, 2011, 2012 Christian Grothoff
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
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 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file dns/gnunet-helper-dns.c
23 * @brief helper to install firewall rules to hijack all DNS traffic
24 * and send it to our virtual interface (except for DNS traffic
25 * that originates on the specified port). We then
26 * allow interacting with our virtual interface via stdin/stdout.
27 * @author Philipp Tölke
28 * @author Christian Grothoff
30 * This program alters the Linux firewall rules so that DNS traffic
31 * that ordinarily exits the system can be intercepted and managed by
32 * a virtual interface. In order to achieve this, DNS traffic is
33 * marked with the DNS_MARK given in below and re-routed to a custom
34 * table with the DNS_TABLE ID given below. Systems and
35 * administrators must take care to not cause conflicts with these
36 * values (it was deemed safest to hardcode them as passing these
37 * values as arguments might permit messing with arbitrary firewall
38 * rules, which would be dangerous).
40 * The code first sets up the virtual interface, then begins to
41 * redirect the DNS traffic to it, and then on errors or SIGTERM shuts
42 * down the virtual interface and removes the rules for the traffic
46 * Note that having this binary SUID is only partially safe: it will
47 * allow redirecting (and intercepting / mangling) of all DNS traffic
48 * originating from this system by any user who is able to run it.
49 * Furthermore, this code will make it trivial to DoS all DNS traffic
50 * originating from the current system, simply by sending it to
51 * nowhere (redirect stdout to /dev/null).
53 * Naturally, neither of these problems can be helped as this is the
54 * fundamental purpose of the binary. Certifying that this code is
55 * "safe" thus only means that it doesn't allow anything else (such
56 * as local priv. escalation, etc.).
58 * The following list of people have reviewed this code and considered
59 * it safe (within specifications) since the last modification (if you
60 * reviewed it, please have your name added to the list):
62 * - Christian Grothoff
66 #include <linux/if_tun.h>
69 * Need 'struct GNUNET_MessageHeader'.
71 #include "gnunet_common.h"
74 * Need DNS message types.
76 #include "gnunet_protocols.h"
79 * Maximum size of a GNUnet message (GNUNET_SERVER_MAX_MESSAGE_SIZE)
81 #define MAX_SIZE 65536
85 * This is in linux/include/net/ipv6.h, but not always exported...
89 struct in6_addr ifr6_addr;
90 uint32_t ifr6_prefixlen;
91 unsigned int ifr6_ifindex;
96 * Name and full path of IPTABLES binary.
98 static const char *sbin_iptables;
101 * Name and full path of IPTABLES binary.
103 static const char *sbin_ip;
106 * Port for DNS traffic.
108 #define DNS_PORT "53"
111 * Marker we set for our hijacked DNS traffic. We use GNUnet's
112 * port (2086) plus the DNS port (53) in HEX to make a 32-bit mark
113 * (which is hopefully long enough to not collide); so
114 * 0x08260035 = 136708149 (hopefully unique enough...).
116 #define DNS_MARK "136708149"
119 * Table we use for our DNS rules. 0-255 is the range and
120 * 0, 253, 254 and 255 are already reserved. As this is about
121 * DNS and as "53" is likely (fingers crossed!) high enough to
122 * not usually conflict with a normal user's setup, we use 53
123 * to give a hint that this has something to do with DNS.
125 #define DNS_TABLE "53"
129 * Control pipe for shutdown via signal. [0] is the read end,
130 * [1] is the write end.
136 * Signal handler called to initiate "nice" shutdown. Signals select
137 * loop via non-bocking pipe 'cpipe'.
139 * @param signal signal number of the signal (not used)
142 signal_handler (int signal)
144 /* ignore return value, as the signal handler could theoretically
145 be called many times before the shutdown can actually happen */
146 (void) write (cpipe[1], "K", 1);
151 * Run the given command and wait for it to complete.
153 * @param file name of the binary to run
154 * @param cmd command line arguments (as given to 'execv')
155 * @return 0 on success, 1 on any error
158 fork_and_exec (const char *file,
175 /* we are the child process */
176 /* close stdin/stdout to not cause interference
177 with the helper's main protocol! */
180 (void) execv (file, cmd);
181 /* can only get here on error */
183 "exec `%s' failed: %s\n",
188 /* keep running waitpid as long as the only error we get is 'EINTR' */
189 while ( (-1 == (ret = waitpid (pid, &status, 0))) &&
194 "waitpid failed: %s\n",
198 if (! (WIFEXITED (status) && (0 == WEXITSTATUS (status))))
200 /* child process completed and returned success, we're happy */
206 * Creates a tun-interface called dev;
208 * @param dev is asumed to point to a char[IFNAMSIZ]
209 * if *dev == '\\0', uses the name supplied by the kernel;
210 * @return the fd to the tun or -1 on error
224 if (-1 == (fd = open ("/dev/net/tun", O_RDWR)))
226 fprintf (stderr, "Error opening `%s': %s\n", "/dev/net/tun",
231 if (fd >= FD_SETSIZE)
233 fprintf (stderr, "File descriptor to large: %d", fd);
237 memset (&ifr, 0, sizeof (ifr));
238 ifr.ifr_flags = IFF_TUN;
241 strncpy (ifr.ifr_name, dev, IFNAMSIZ);
243 if (-1 == ioctl (fd, TUNSETIFF, (void *) &ifr))
245 fprintf (stderr, "Error with ioctl on `%s': %s\n", "/dev/net/tun",
250 strcpy (dev, ifr.ifr_name);
256 * @brief Sets the IPv6-Address given in address on the interface dev
258 * @param dev the interface to configure
259 * @param address the IPv6-Address
260 * @param prefix_len the length of the network-prefix
263 set_address6 (const char *dev, const char *address, unsigned long prefix_len)
266 struct in6_ifreq ifr6;
267 struct sockaddr_in6 sa6;
271 * parse the new address
273 memset (&sa6, 0, sizeof (struct sockaddr_in6));
274 sa6.sin6_family = AF_INET6;
275 if (1 != inet_pton (AF_INET6, address, sa6.sin6_addr.s6_addr))
277 fprintf (stderr, "Failed to parse address `%s': %s\n", address,
282 if (-1 == (fd = socket (PF_INET6, SOCK_DGRAM, 0)))
284 fprintf (stderr, "Error creating socket: %s\n", strerror (errno));
288 memset (&ifr, 0, sizeof (struct ifreq));
290 * Get the index of the if
292 strncpy (ifr.ifr_name, dev, IFNAMSIZ);
293 if (-1 == ioctl (fd, SIOGIFINDEX, &ifr))
295 fprintf (stderr, "ioctl failed at %d: %s\n", __LINE__, strerror (errno));
300 memset (&ifr6, 0, sizeof (struct in6_ifreq));
301 ifr6.ifr6_addr = sa6.sin6_addr;
302 ifr6.ifr6_ifindex = ifr.ifr_ifindex;
303 ifr6.ifr6_prefixlen = prefix_len;
308 if (-1 == ioctl (fd, SIOCSIFADDR, &ifr6))
310 fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
319 if (-1 == ioctl (fd, SIOCGIFFLAGS, &ifr))
321 fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
328 * Add the UP and RUNNING flags
330 ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
331 if (-1 == ioctl (fd, SIOCSIFFLAGS, &ifr))
333 fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
341 fprintf (stderr, "close failed: %s\n", strerror (errno));
348 * @brief Sets the IPv4-Address given in address on the interface dev
350 * @param dev the interface to configure
351 * @param address the IPv4-Address
352 * @param mask the netmask
355 set_address4 (const char *dev, const char *address, const char *mask)
358 struct sockaddr_in *addr;
361 memset (&ifr, 0, sizeof (struct ifreq));
362 addr = (struct sockaddr_in *) &(ifr.ifr_addr);
363 addr->sin_family = AF_INET;
368 if (1 != inet_pton (AF_INET, address, &addr->sin_addr.s_addr))
370 fprintf (stderr, "Failed to parse address `%s': %s\n", address,
375 if (-1 == (fd = socket (PF_INET, SOCK_DGRAM, 0)))
377 fprintf (stderr, "Error creating socket: %s\n", strerror (errno));
381 strncpy (ifr.ifr_name, dev, IFNAMSIZ);
386 if (-1 == ioctl (fd, SIOCSIFADDR, &ifr))
388 fprintf (stderr, "ioctl failed at %d: %s\n", __LINE__, strerror (errno));
396 addr = (struct sockaddr_in *) &(ifr.ifr_netmask);
397 if (1 != inet_pton (AF_INET, mask, &addr->sin_addr.s_addr))
399 fprintf (stderr, "Failed to parse address `%s': %s\n", mask,
408 if (-1 == ioctl (fd, SIOCSIFNETMASK, &ifr))
410 fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
419 if (-1 == ioctl (fd, SIOCGIFFLAGS, &ifr))
421 fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
428 * Add the UP and RUNNING flags
430 ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
431 if (-1 == ioctl (fd, SIOCSIFFLAGS, &ifr))
433 fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
441 fprintf (stderr, "close failed: %s\n", strerror (errno));
449 * Start forwarding to and from the tunnel. This function runs with
450 * "reduced" priviledges (saved UID is still 0, but effective UID is
453 * @param fd_tun tunnel FD
459 * The buffer filled by reading from fd_tun
461 unsigned char buftun[MAX_SIZE];
462 ssize_t buftun_size = 0;
463 unsigned char *buftun_read = NULL;
466 * The buffer filled by reading from stdin
468 unsigned char bufin[MAX_SIZE];
469 ssize_t bufin_size = 0;
470 size_t bufin_rpos = 0;
471 unsigned char *bufin_read = NULL;
482 * We are supposed to read and the buffer is empty
483 * -> select on read from tun
485 if (0 == buftun_size)
486 FD_SET (fd_tun, &fds_r);
489 * We are supposed to read and the buffer is not empty
490 * -> select on write to stdout
492 if (0 != buftun_size)
496 * We are supposed to write and the buffer is empty
497 * -> select on read from stdin
499 if (NULL == bufin_read)
503 * We are supposed to write and the buffer is not empty
504 * -> select on write to tun
506 if (NULL != bufin_read)
507 FD_SET (fd_tun, &fds_w);
509 FD_SET (cpipe[0], &fds_r);
510 max = (fd_tun > cpipe[0]) ? fd_tun : cpipe[0];
512 int r = select (max + 1, &fds_r, &fds_w, NULL, NULL);
518 fprintf (stderr, "select failed: %s\n", strerror (errno));
524 if (FD_ISSET (cpipe[0], &fds_r))
525 return; /* aborted by signal */
527 if (FD_ISSET (fd_tun, &fds_r))
530 read (fd_tun, buftun + sizeof (struct GNUNET_MessageHeader),
531 MAX_SIZE - sizeof (struct GNUNET_MessageHeader));
532 if (-1 == buftun_size)
534 if ( (errno == EINTR) ||
537 fprintf (stderr, "read-error: %s\n", strerror (errno));
540 if (0 == buftun_size)
542 fprintf (stderr, "EOF on tun\n");
545 buftun_read = buftun;
547 struct GNUNET_MessageHeader *hdr =
548 (struct GNUNET_MessageHeader *) buftun;
549 buftun_size += sizeof (struct GNUNET_MessageHeader);
550 hdr->type = htons (GNUNET_MESSAGE_TYPE_DNS_HELPER);
551 hdr->size = htons (buftun_size);
554 else if (FD_ISSET (1, &fds_w))
556 ssize_t written = write (1, buftun_read, buftun_size);
560 if ( (errno == EINTR) ||
563 fprintf (stderr, "write-error to stdout: %s\n", strerror (errno));
568 fprintf (stderr, "write returned 0\n");
571 buftun_size -= written;
572 buftun_read += written;
575 if (FD_ISSET (0, &fds_r))
577 bufin_size = read (0, bufin + bufin_rpos, MAX_SIZE - bufin_rpos);
578 if (-1 == bufin_size)
581 if ( (errno == EINTR) ||
584 fprintf (stderr, "read-error: %s\n", strerror (errno));
590 fprintf (stderr, "EOF on stdin\n");
594 struct GNUNET_MessageHeader *hdr;
597 bufin_rpos += bufin_size;
598 if (bufin_rpos < sizeof (struct GNUNET_MessageHeader))
600 hdr = (struct GNUNET_MessageHeader *) bufin;
601 if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_DNS_HELPER)
603 fprintf (stderr, "protocol violation!\n");
606 if (ntohs (hdr->size) > bufin_rpos)
608 bufin_read = bufin + sizeof (struct GNUNET_MessageHeader);
609 bufin_size = ntohs (hdr->size) - sizeof (struct GNUNET_MessageHeader);
610 bufin_rpos -= bufin_size + sizeof (struct GNUNET_MessageHeader);
613 else if (FD_ISSET (fd_tun, &fds_w))
615 ssize_t written = write (fd_tun, bufin_read, bufin_size);
619 if ( (errno == EINTR) ||
622 fprintf (stderr, "write-error to tun: %s\n", strerror (errno));
627 fprintf (stderr, "write returned 0\n");
631 bufin_size -= written;
632 bufin_read += written;
635 memmove (bufin, bufin_read, bufin_rpos);
636 bufin_read = NULL; /* start reading again */
648 * Main function of "gnunet-helper-dns", which opens a VPN tunnel interface,
649 * redirects all outgoing DNS traffic (except from the specified port) to that
650 * interface and then passes traffic from and to the interface via stdin/stdout.
652 * Once stdin/stdout close or have other errors, the tunnel is closed and the
653 * DNS traffic redirection is stopped.
655 * @param argc number of arguments
656 * @param argv 0: binary name (should be "gnunet-helper-vpn")
657 * 1: tunnel interface name (typically "gnunet-dns")
658 * 2: IPv6 address for the tunnel ("FE80::1")
659 * 3: IPv6 netmask length in bits ("64")
660 * 4: IPv4 address for the tunnel ("1.2.3.4")
661 * 5: IPv4 netmask ("255.255.0.0")
662 * 6: PORT to not hijack ("55533")
663 * @return 0 on success, otherwise code indicating type of error:
664 * 1 wrong number of arguments
665 * 2 invalid arguments (i.e. port number / prefix length wrong)
666 * 3 iptables not executable
667 * 4 ip not executable
668 * 5 failed to initialize tunnel interface
669 * 6 failed to initialize control pipe
670 * 8 failed to change routing table, cleanup successful
671 * 9-23 failed to change routing table and failed to undo some changes to routing table
672 * 24 failed to drop privs
673 * 25-39 failed to drop privs and then failed to undo some changes to routing table
674 * 40 failed to regain privs
675 * 41-55 failed to regain prisv and then failed to undo some changes to routing table
676 * 255 failed to handle kill signal properly
679 main (int argc, char *const*argv)
689 fprintf (stderr, "Fatal: must supply 6 arguments!\n");
693 /* verify that the binaries were care about are executable */
694 if (0 == access ("/sbin/iptables", X_OK))
695 sbin_iptables = "/sbin/iptables";
696 else if (0 == access ("/usr/sbin/iptables", X_OK))
697 sbin_iptables = "/usr/sbin/iptables";
701 "Fatal: executable iptables not found in approved directories: %s\n",
705 if (0 == access ("/sbin/ip", X_OK))
706 sbin_ip = "/sbin/ip";
707 else if (0 == access ("/usr/sbin/ip", X_OK))
708 sbin_ip = "/usr/sbin/ip";
712 "Fatal: executable ip not found in approved directories: %s\n",
717 /* validate port number */
718 port = atoi (argv[6]);
719 if ( (port == 0) || (port >= 65536) )
722 "Port `%u' is invalid\n",
726 /* print port number to string for command-line use*/
727 (void) snprintf (localport,
732 /* do not die on SIGPIPE */
733 if (SIG_ERR == signal (SIGPIPE, SIG_IGN))
735 fprintf (stderr, "Failed to protect against SIGPIPE: %s\n",
740 /* setup pipe to shutdown nicely on SIGINT */
741 if (0 != pipe (cpipe))
744 "Fatal: could not setup control pipe: %s\n",
748 if (cpipe[0] >= FD_SETSIZE)
750 fprintf (stderr, "Pipe file descriptor to large: %d", cpipe[0]);
751 (void) close (cpipe[0]);
752 (void) close (cpipe[1]);
756 /* make pipe non-blocking, as we theoretically could otherwise block
757 in the signal handler */
758 int flags = fcntl (cpipe[1], F_GETFL);
761 fprintf (stderr, "Failed to read flags for pipe: %s", strerror (errno));
762 (void) close (cpipe[0]);
763 (void) close (cpipe[1]);
767 if (0 != fcntl (cpipe[1], F_SETFL, flags))
769 fprintf (stderr, "Failed to make pipe non-blocking: %s", strerror (errno));
770 (void) close (cpipe[0]);
771 (void) close (cpipe[1]);
775 if ( (SIG_ERR == signal (SIGTERM, &signal_handler)) ||
776 (SIG_ERR == signal (SIGINT, &signal_handler)) ||
777 (SIG_ERR == signal (SIGHUP, &signal_handler)) )
780 "Fatal: could not initialize signal handler: %s\n",
782 (void) close (cpipe[0]);
783 (void) close (cpipe[1]);
788 /* get interface name */
789 strncpy (dev, argv[1], IFNAMSIZ);
790 dev[IFNAMSIZ - 1] = '\0';
792 /* now open virtual interface (first part that requires root) */
793 if (-1 == (fd_tun = init_tun (dev)))
795 fprintf (stderr, "Fatal: could not initialize tun-interface\n");
796 (void) signal (SIGTERM, SIG_IGN);
797 (void) signal (SIGINT, SIG_IGN);
798 (void) signal (SIGHUP, SIG_IGN);
799 (void) close (cpipe[0]);
800 (void) close (cpipe[1]);
804 /* now set interface addresses */
806 const char *address = argv[2];
807 long prefix_len = atol (argv[3]);
809 if ((prefix_len < 1) || (prefix_len > 127))
811 fprintf (stderr, "Fatal: prefix_len out of range\n");
812 (void) signal (SIGTERM, SIG_IGN);
813 (void) signal (SIGINT, SIG_IGN);
814 (void) signal (SIGHUP, SIG_IGN);
815 (void) close (cpipe[0]);
816 (void) close (cpipe[1]);
819 set_address6 (dev, address, prefix_len);
823 const char *address = argv[4];
824 const char *mask = argv[5];
826 set_address4 (dev, address, mask);
829 /* update routing tables -- next part why we need SUID! */
830 /* Forward everything from the given local port (with destination
831 to port 53, and only for UDP) without hijacking */
832 r = 8; /* failed to fully setup routing table */
834 char *const mangle_args[] =
836 "iptables", "-t", "mangle", "-I", "OUTPUT", "1", "-p",
837 "udp", "--sport", localport, "--dport", DNS_PORT, "-j",
840 if (0 != fork_and_exec (sbin_iptables, mangle_args))
843 /* Mark all of the other DNS traffic using our mark DNS_MARK */
845 char *const mark_args[] =
847 "iptables", "-t", "mangle", "-I", "OUTPUT", "2", "-p",
848 "udp", "--dport", DNS_PORT, "-j", "MARK", "--set-mark", DNS_MARK,
851 if (0 != fork_and_exec (sbin_iptables, mark_args))
852 goto cleanup_mangle_1;
854 /* Forward all marked DNS traffic to our DNS_TABLE */
856 char *const forward_args[] =
858 "ip", "rule", "add", "fwmark", DNS_MARK, "table", DNS_TABLE, NULL
860 if (0 != fork_and_exec (sbin_ip, forward_args))
863 /* Finally, add rule in our forwarding table to pass to our virtual interface */
865 char *const route_args[] =
867 "ip", "route", "add", "default", "dev", dev,
868 "table", DNS_TABLE, NULL
870 if (0 != fork_and_exec (sbin_ip, route_args))
871 goto cleanup_forward_3;
874 /* drop privs *except* for the saved UID; this is not perfect, but better
875 than doing nothing */
876 uid_t uid = getuid ();
877 #ifdef HAVE_SETRESUID
878 if (0 != setresuid (uid, uid, 0))
880 fprintf (stderr, "Failed to setresuid: %s\n", strerror (errno));
882 goto cleanup_route_4;
885 /* Note: no 'setuid' here as we must keep our saved UID as root */
886 if (0 != seteuid (uid))
888 fprintf (stderr, "Failed to seteuid: %s\n", strerror (errno));
890 goto cleanup_route_4;
894 r = 0; /* did fully setup routing table (if nothing else happens, we were successful!) */
896 /* now forward until we hit a problem */
899 /* now need to regain privs so we can remove the firewall rules we added! */
900 #ifdef HAVE_SETRESUID
901 if (0 != setresuid (uid, 0, 0))
903 fprintf (stderr, "Failed to setresuid back to root: %s\n", strerror (errno));
905 goto cleanup_route_4;
908 if (0 != seteuid (0))
910 fprintf (stderr, "Failed to seteuid back to root: %s\n", strerror (errno));
912 goto cleanup_route_4;
916 /* update routing tables again -- this is why we could not fully drop privs */
917 /* now undo updating of routing tables; normal exit or clean-up-on-error case */
920 char *const route_clean_args[] =
922 "ip", "route", "del", "default", "dev", dev,
923 "table", DNS_TABLE, NULL
925 if (0 != fork_and_exec (sbin_ip, route_clean_args))
930 char *const forward_clean_args[] =
932 "ip", "rule", "del", "fwmark", DNS_MARK, "table", DNS_TABLE, NULL
934 if (0 != fork_and_exec (sbin_ip, forward_clean_args))
939 char *const mark_clean_args[] =
941 "iptables", "-t", "mangle", "-D", "OUTPUT", "-p", "udp",
942 "--dport", DNS_PORT, "-j", "MARK", "--set-mark", DNS_MARK, NULL
944 if (0 != fork_and_exec (sbin_iptables, mark_clean_args))
949 char *const mangle_clean_args[] =
951 "iptables", "-t", "mangle", "-D", "OUTPUT", "-p", "udp",
952 "--sport", localport, "--dport", DNS_PORT, "-j", "ACCEPT",
955 if (0 != fork_and_exec (sbin_iptables, mangle_clean_args))
960 /* close virtual interface */
961 (void) close (fd_tun);
962 /* remove signal handler so we can close the pipes */
963 (void) signal (SIGTERM, SIG_IGN);
964 (void) signal (SIGINT, SIG_IGN);
965 (void) signal (SIGHUP, SIG_IGN);
966 (void) close (cpipe[0]);
967 (void) close (cpipe[1]);
971 /* end of gnunet-helper-dns.c */