db1401e89944a838b8fa207dc6c2e4739642898a
[oweals/gnunet.git] / src / exit / gnunet-helper-exit.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010, 2011, 2012 Christian Grothoff
4
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.
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      General Public License for more details.
14
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.
19 */
20
21 /**
22  * @file exit/gnunet-helper-exit.c 
23  *
24  * @brief the helper for exit nodes. Opens a virtual
25  * network-interface, sends data received on the if to stdout, sends
26  * data received on stdin to the interface.  The code also enables
27  * IPv4/IPv6 forwarding and NAT on the current system (the latter on
28  * an interface specified on the command-line); these changes to the
29  * network configuration are NOT automatically undone when the program
30  * is stopped (this is because we cannot be sure that some other
31  * application didn't enable them before or after us; also, these
32  * changes should be mostly harmless as it simply turns the system
33  * into a router).
34  *
35  * @author Philipp Tölke
36  * @author Christian Grothoff
37  *
38  * The following list of people have reviewed this code and considered
39  * it safe since the last modification (if you reviewed it, please
40  * have your name added to the list):
41  *
42  * - Philipp Tölke
43  */
44 #include "platform.h"
45 #include <linux/if_tun.h>
46
47 /**
48  * Need 'struct GNUNET_MessageHeader'.
49  */
50 #include "gnunet_common.h"
51
52 /**
53  * Need VPN message types.
54  */
55 #include "gnunet_protocols.h"
56
57 /**
58  * Maximum size of a GNUnet message (GNUNET_SERVER_MAX_MESSAGE_SIZE)
59  */
60 #define MAX_SIZE 65536
61
62 /**
63  * Path to 'sysctl' binary.
64  */
65 static const char *sbin_sysctl;
66
67 /**
68  * Path to 'iptables' binary.
69  */
70 static const char *sbin_iptables;
71
72
73 #ifndef _LINUX_IN6_H
74 /**
75  * This is in linux/include/net/ipv6.h, but not always exported...
76  */
77 struct in6_ifreq
78 {
79   struct in6_addr ifr6_addr;
80   uint32_t ifr6_prefixlen;
81   unsigned int ifr6_ifindex;
82 };
83 #endif
84
85
86
87 /**
88  * Run the given command and wait for it to complete.
89  * 
90  * @param file name of the binary to run
91  * @param cmd command line arguments (as given to 'execv')
92  * @return 0 on success, 1 on any error
93  */
94 static int
95 fork_and_exec (const char *file, 
96                char *const cmd[])
97 {
98   int status;
99   pid_t pid;
100   pid_t ret;
101
102   pid = fork ();
103   if (-1 == pid)
104   {
105     fprintf (stderr, 
106              "fork failed: %s\n", 
107              strerror (errno));
108     return 1;
109   }
110   if (0 == pid)
111   {
112     /* we are the child process */
113     /* close stdin/stdout to not cause interference
114        with the helper's main protocol! */
115     (void) close (0); 
116     (void) close (1); 
117     (void) execv (file, cmd);
118     /* can only get here on error */
119     fprintf (stderr, 
120              "exec `%s' failed: %s\n", 
121              file,
122              strerror (errno));
123     _exit (1);
124   }
125   /* keep running waitpid as long as the only error we get is 'EINTR' */
126   while ( (-1 == (ret = waitpid (pid, &status, 0))) &&
127           (errno == EINTR) ); 
128   if (-1 == ret)
129   {
130     fprintf (stderr, 
131              "waitpid failed: %s\n", 
132              strerror (errno));
133     return 1;
134   }
135   if (! (WIFEXITED (status) && (0 == WEXITSTATUS (status))))
136     return 1;
137   /* child process completed and returned success, we're happy */
138   return 0;
139 }
140
141
142 /**
143  * Creates a tun-interface called dev;
144  *
145  * @param dev is asumed to point to a char[IFNAMSIZ]
146  *        if *dev == '\\0', uses the name supplied by the kernel;
147  * @return the fd to the tun or -1 on error
148  */
149 static int
150 init_tun (char *dev)
151 {
152   struct ifreq ifr;
153   int fd;
154
155   if (NULL == dev)
156   {
157     errno = EINVAL;
158     return -1;
159   }
160
161   if (-1 == (fd = open ("/dev/net/tun", O_RDWR)))
162   {
163     fprintf (stderr, "Error opening `%s': %s\n", "/dev/net/tun",
164              strerror (errno));
165     return -1;
166   }
167
168   if (fd >= FD_SETSIZE)
169   {
170     fprintf (stderr, "File descriptor to large: %d", fd);
171     (void) close (fd);
172     return -1;
173   }
174
175   memset (&ifr, 0, sizeof (ifr));
176   ifr.ifr_flags = IFF_TUN;
177
178   if ('\0' != *dev)
179     strncpy (ifr.ifr_name, dev, IFNAMSIZ);
180
181   if (-1 == ioctl (fd, TUNSETIFF, (void *) &ifr))
182   {
183     fprintf (stderr, 
184              "Error with ioctl on `%s': %s\n", "/dev/net/tun",
185              strerror (errno));
186     (void) close (fd);
187     return -1;
188   }
189   strcpy (dev, ifr.ifr_name);
190   return fd;
191 }
192
193
194 /**
195  * @brief Sets the IPv6-Address given in address on the interface dev
196  *
197  * @param dev the interface to configure
198  * @param address the IPv6-Address
199  * @param prefix_len the length of the network-prefix
200  */
201 static void
202 set_address6 (const char *dev, const char *address, unsigned long prefix_len)
203 {
204   struct ifreq ifr;
205   struct in6_ifreq ifr6;
206   struct sockaddr_in6 sa6;
207   int fd;
208
209   /*
210    * parse the new address
211    */
212   memset (&sa6, 0, sizeof (struct sockaddr_in6));
213   sa6.sin6_family = AF_INET6;
214   if (1 != inet_pton (AF_INET6, address, sa6.sin6_addr.s6_addr))
215   {
216     fprintf (stderr, "Failed to parse address `%s': %s\n", address,
217              strerror (errno));
218     exit (1);
219   }
220
221   if (-1 == (fd = socket (PF_INET6, SOCK_DGRAM, 0)))
222   {
223     fprintf (stderr, "Error creating socket: %s\n", strerror (errno));
224     exit (1);
225   }
226
227   memset (&ifr, 0, sizeof (struct ifreq));
228   /*
229    * Get the index of the if
230    */
231   strncpy (ifr.ifr_name, dev, IFNAMSIZ);
232   if (-1 == ioctl (fd, SIOGIFINDEX, &ifr))
233   {
234     fprintf (stderr, "ioctl failed at %d: %s\n", __LINE__, strerror (errno));
235     (void) close (fd);
236     exit (1);
237   }
238
239   memset (&ifr6, 0, sizeof (struct in6_ifreq));
240   ifr6.ifr6_addr = sa6.sin6_addr;
241   ifr6.ifr6_ifindex = ifr.ifr_ifindex;
242   ifr6.ifr6_prefixlen = prefix_len;
243
244   /*
245    * Set the address
246    */
247   if (-1 == ioctl (fd, SIOCSIFADDR, &ifr6))
248   {
249     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
250              strerror (errno));
251     (void) close (fd);
252     exit (1);
253   }
254
255   /*
256    * Get the flags
257    */
258   if (-1 == ioctl (fd, SIOCGIFFLAGS, &ifr))
259   {
260     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
261              strerror (errno));
262     (void) close (fd);
263     exit (1);
264   }
265
266   /*
267    * Add the UP and RUNNING flags
268    */
269   ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
270   if (-1 == ioctl (fd, SIOCSIFFLAGS, &ifr))
271   {
272     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
273              strerror (errno));
274     (void) close (fd);
275     exit (1);
276   }
277
278   if (0 != close (fd))
279   {
280     fprintf (stderr, "close failed: %s\n", strerror (errno));
281     exit (1);
282   }
283 }
284
285
286 /**
287  * @brief Sets the IPv4-Address given in address on the interface dev
288  *
289  * @param dev the interface to configure
290  * @param address the IPv4-Address
291  * @param mask the netmask
292  */
293 static void
294 set_address4 (const char *dev, const char *address, const char *mask)
295 {
296   int fd;
297   struct sockaddr_in *addr;
298   struct ifreq ifr;
299
300   memset (&ifr, 0, sizeof (struct ifreq));
301   addr = (struct sockaddr_in *) &(ifr.ifr_addr);
302   addr->sin_family = AF_INET;
303
304   /*
305    * Parse the address
306    */
307   if (1 != inet_pton (AF_INET, address, &addr->sin_addr.s_addr))
308   {
309     fprintf (stderr, "Failed to parse address `%s': %s\n", address,
310              strerror (errno));
311     exit (1);
312   }
313
314   if (-1 == (fd = socket (PF_INET, SOCK_DGRAM, 0)))
315   {
316     fprintf (stderr, "Error creating socket: %s\n", strerror (errno));
317     exit (1);
318   }
319
320   strncpy (ifr.ifr_name, dev, IFNAMSIZ);
321
322   /*
323    * Set the address
324    */
325   if (-1 == ioctl (fd, SIOCSIFADDR, &ifr))
326   {
327     fprintf (stderr, "ioctl failed at %d: %s\n", __LINE__, strerror (errno));
328     (void) close (fd);
329     exit (1);
330   }
331
332   /*
333    * Parse the netmask
334    */
335   addr = (struct sockaddr_in *) &(ifr.ifr_netmask);
336   if (1 != inet_pton (AF_INET, mask, &addr->sin_addr.s_addr))
337   {
338     fprintf (stderr, "Failed to parse address `%s': %s\n", mask,
339              strerror (errno));
340     (void) close (fd);
341     exit (1);
342   }
343
344   /*
345    * Set the netmask
346    */
347   if (-1 == ioctl (fd, SIOCSIFNETMASK, &ifr))
348   {
349     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
350              strerror (errno));
351     (void) close (fd);
352     exit (1);
353   }
354
355   /*
356    * Get the flags
357    */
358   if (-1 == ioctl (fd, SIOCGIFFLAGS, &ifr))
359   {
360     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
361              strerror (errno));
362     (void) close (fd);
363     exit (1);
364   }
365
366   /*
367    * Add the UP and RUNNING flags
368    */
369   ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
370   if (-1 == ioctl (fd, SIOCSIFFLAGS, &ifr))
371   {
372     fprintf (stderr, "ioctl failed at line %d: %s\n", __LINE__,
373              strerror (errno));
374     (void) close (fd);
375     exit (1);
376   }
377
378   if (0 != close (fd))
379   {
380     fprintf (stderr, "close failed: %s\n", strerror (errno));
381     (void) close (fd);
382     exit (1);
383   }
384 }
385
386
387 /**
388  * Start forwarding to and from the tunnel.
389  *
390  * @param fd_tun tunnel FD
391  */
392 static void
393 run (int fd_tun)
394 {
395   /*
396    * The buffer filled by reading from fd_tun
397    */
398   unsigned char buftun[MAX_SIZE];
399   ssize_t buftun_size = 0;
400   unsigned char *buftun_read = NULL;
401
402   /*
403    * The buffer filled by reading from stdin
404    */
405   unsigned char bufin[MAX_SIZE];
406   ssize_t bufin_size = 0;
407   size_t bufin_rpos = 0;
408   unsigned char *bufin_read = NULL;
409
410   fd_set fds_w;
411   fd_set fds_r;
412
413   /* read refers to reading from fd_tun, writing to stdout */
414   int read_open = 1;
415
416   /* write refers to reading from stdin, writing to fd_tun */
417   int write_open = 1;
418
419   while ((1 == read_open) || (1 == write_open))
420   {
421     FD_ZERO (&fds_w);
422     FD_ZERO (&fds_r);
423
424     /*
425      * We are supposed to read and the buffer is empty
426      * -> select on read from tun
427      */
428     if (read_open && (0 == buftun_size))
429       FD_SET (fd_tun, &fds_r);
430
431     /*
432      * We are supposed to read and the buffer is not empty
433      * -> select on write to stdout
434      */
435     if (read_open && (0 != buftun_size))
436       FD_SET (1, &fds_w);
437
438     /*
439      * We are supposed to write and the buffer is empty
440      * -> select on read from stdin
441      */
442     if (write_open && (NULL == bufin_read))
443       FD_SET (0, &fds_r);
444
445     /*
446      * We are supposed to write and the buffer is not empty
447      * -> select on write to tun
448      */
449     if (write_open && (NULL != bufin_read))
450       FD_SET (fd_tun, &fds_w);
451
452     int r = select (fd_tun + 1, &fds_r, &fds_w, NULL, NULL);
453
454     if (-1 == r)
455     {
456       if (EINTR == errno)
457         continue;
458       fprintf (stderr, "select failed: %s\n", strerror (errno));
459       exit (1);
460     }
461
462     if (r > 0)
463     {
464       if (FD_ISSET (fd_tun, &fds_r))
465       {
466         buftun_size =
467             read (fd_tun, buftun + sizeof (struct GNUNET_MessageHeader),
468                   MAX_SIZE - sizeof (struct GNUNET_MessageHeader));
469         if (-1 == buftun_size)
470         {
471           fprintf (stderr, "read-error: %s\n", strerror (errno));
472           shutdown (fd_tun, SHUT_RD);
473           shutdown (1, SHUT_WR);
474           read_open = 0;
475           buftun_size = 0;
476         }
477         else if (0 == buftun_size)
478         {
479           fprintf (stderr, "EOF on tun\n");
480           shutdown (fd_tun, SHUT_RD);
481           shutdown (1, SHUT_WR);
482           read_open = 0;
483           buftun_size = 0;
484         }
485         else
486         {
487           buftun_read = buftun;
488           struct GNUNET_MessageHeader *hdr =
489               (struct GNUNET_MessageHeader *) buftun;
490           buftun_size += sizeof (struct GNUNET_MessageHeader);
491           hdr->type = htons (GNUNET_MESSAGE_TYPE_VPN_HELPER);
492           hdr->size = htons (buftun_size);
493         }
494       }
495       else if (FD_ISSET (1, &fds_w))
496       {
497         ssize_t written = write (1, buftun_read, buftun_size);
498
499         if (-1 == written)
500         {
501           fprintf (stderr, "write-error to stdout: %s\n", strerror (errno));
502           shutdown (fd_tun, SHUT_RD);
503           shutdown (1, SHUT_WR);
504           read_open = 0;
505           buftun_size = 0;
506         }
507         else if (0 == written)
508         {
509           fprintf (stderr, "write returned 0!?\n");
510           exit (1);
511         }
512         else
513         {
514           buftun_size -= written;
515           buftun_read += written;
516         }
517       }
518
519       if (FD_ISSET (0, &fds_r))
520       {
521         bufin_size = read (0, bufin + bufin_rpos, MAX_SIZE - bufin_rpos);
522         if (-1 == bufin_size)
523         {
524           fprintf (stderr, "read-error: %s\n", strerror (errno));
525           shutdown (0, SHUT_RD);
526           shutdown (fd_tun, SHUT_WR);
527           write_open = 0;
528           bufin_size = 0;
529         }
530         else if (0 == bufin_size)
531         {
532           fprintf (stderr, "EOF on stdin\n");
533           shutdown (0, SHUT_RD);
534           shutdown (fd_tun, SHUT_WR);
535           write_open = 0;
536           bufin_size = 0;
537         }
538         else
539         {
540           struct GNUNET_MessageHeader *hdr;
541
542 PROCESS_BUFFER:
543           bufin_rpos += bufin_size;
544           if (bufin_rpos < sizeof (struct GNUNET_MessageHeader))
545             continue;
546           hdr = (struct GNUNET_MessageHeader *) bufin;
547           if (ntohs (hdr->type) != GNUNET_MESSAGE_TYPE_VPN_HELPER)
548           {
549             fprintf (stderr, "protocol violation!\n");
550             exit (1);
551           }
552           if (ntohs (hdr->size) > bufin_rpos)
553             continue;
554           bufin_read = bufin + sizeof (struct GNUNET_MessageHeader);
555           bufin_size = ntohs (hdr->size) - sizeof (struct GNUNET_MessageHeader);
556           bufin_rpos -= bufin_size + sizeof (struct GNUNET_MessageHeader);
557         }
558       }
559       else if (FD_ISSET (fd_tun, &fds_w))
560       {
561         ssize_t written = write (fd_tun, bufin_read, bufin_size);
562
563         if (-1 == written)
564         {
565           fprintf (stderr, "write-error to tun: %s\n", strerror (errno));
566           shutdown (0, SHUT_RD);
567           shutdown (fd_tun, SHUT_WR);
568           write_open = 0;
569           bufin_size = 0;
570         }
571         else if (0 == written)
572         {
573           fprintf (stderr, "write returned 0!?\n");
574           exit (1);
575         }
576         else
577         {
578           bufin_size -= written;
579           bufin_read += written;
580           if (0 == bufin_size)
581           {
582             memmove (bufin, bufin_read, bufin_rpos);
583             bufin_read = NULL;  /* start reading again */
584             bufin_size = 0;
585             goto PROCESS_BUFFER;
586           }
587         }
588       }
589     }
590   }
591 }
592
593
594 /**
595  * Open VPN tunnel interface.
596  *
597  * @param argc must be 6
598  * @param argv 0: binary name ("gnunet-helper-exit")
599  *             1: tunnel interface name ("gnunet-exit")
600  *             2: IPv4 "physical" interface name ("eth0"), or "%" to not do IPv4 NAT
601  *             3: IPv6 address ("::1"), or "-" to skip IPv6
602  *             4: IPv6 netmask length in bits ("64") [ignored if #4 is "-"]
603  *             5: IPv4 address ("1.2.3.4"), or "-" to skip IPv4
604  *             6: IPv4 netmask ("255.255.0.0") [ignored if #4 is "-"]
605  */
606 int
607 main (int argc, char **argv)
608 {
609   char dev[IFNAMSIZ];
610   int fd_tun;
611   int global_ret;
612
613   if (7 != argc)
614   {
615     fprintf (stderr, "Fatal: must supply 6 arguments!\n");
616     return 1;
617   }
618   if ( (0 == strcmp (argv[3], "-")) &&
619        (0 == strcmp (argv[5], "-")) )
620   {
621     fprintf (stderr, "Fatal: disabling both IPv4 and IPv6 makes no sense.\n");
622     return 1;
623   }
624   if (0 == access ("/sbin/iptables", X_OK))
625     sbin_iptables = "/sbin/iptables";
626   else if (0 == access ("/usr/sbin/iptables", X_OK))
627     sbin_iptables = "/usr/sbin/iptables";
628   else
629   {
630     fprintf (stderr, 
631              "Fatal: executable iptables not found in approved directories: %s\n",
632              strerror (errno));
633     return 1;
634   }
635   if (0 == access ("/sbin/sysctl", X_OK))
636     sbin_sysctl = "/sbin/sysctl";
637   else if (0 == access ("/usr/sbin/sysctl", X_OK))
638     sbin_sysctl = "/usr/sbin/sysctl";
639   else
640   {
641     fprintf (stderr,
642              "Fatal: executable sysctl not found in approved directories: %s\n",
643              strerror (errno));
644     return 1;
645   }
646
647   strncpy (dev, argv[1], IFNAMSIZ);
648   dev[IFNAMSIZ - 1] = '\0';
649
650   if (-1 == (fd_tun = init_tun (dev)))
651   {
652     fprintf (stderr, "Fatal: could not initialize tun-interface\n");
653     return 1;
654   }
655
656   if (0 != strcmp (argv[3], "-"))
657   {
658     {
659       const char *address = argv[3];
660       long prefix_len = atol (argv[4]);
661       
662       if ((prefix_len < 1) || (prefix_len > 127))
663       {
664         fprintf (stderr, "Fatal: prefix_len out of range\n");
665         return 1;
666       }      
667       set_address6 (dev, address, prefix_len);    
668     }
669     {
670       char *const sysctl_args[] =
671         {
672           "sysctl", "-w", "net.ipv6.conf.all.forwarding=1", NULL
673         };
674       if (0 != fork_and_exec (sbin_sysctl,
675                               sysctl_args))
676       {
677         fprintf (stderr,
678                  "Failed to enable IPv6 forwarding.  Will continue anyway.\n");
679       }    
680     }
681   }
682
683   if (0 != strcmp (argv[5], "-"))
684   {
685     {
686       const char *address = argv[5];
687       const char *mask = argv[6];
688       
689       set_address4 (dev, address, mask);
690     }
691     {
692       char *const sysctl_args[] =
693         {
694           "sysctl", "-w", "net.ipv4.ip_forward=1", NULL
695         };
696       if (0 != fork_and_exec (sbin_sysctl,
697                               sysctl_args))
698       {
699         fprintf (stderr,
700                  "Failed to enable IPv4 forwarding.  Will continue anyway.\n");
701       }    
702     }
703     if (0 != strcmp (argv[2], "%"))
704     {
705       char *const iptables_args[] =
706         {
707           "iptables", "-t", "nat", "-A", "POSTROUTING", "-o", argv[2], "-j", "MASQUERADE", NULL
708         };
709       if (0 != fork_and_exec (sbin_iptables,
710                               iptables_args))
711       {
712         fprintf (stderr,
713                  "Failed to enable IPv4 masquerading (NAT).  Will continue anyway.\n");
714       }    
715     }
716   }
717   
718   uid_t uid = getuid ();
719 #ifdef HAVE_SETRESUID
720   if (0 != setresuid (uid, uid, uid))
721   {
722     fprintf (stderr, "Failed to setresuid: %s\n", strerror (errno));
723     global_ret = 2;
724     goto cleanup;
725   }
726 #else
727   if (0 != (setuid (uid) | seteuid (uid)))
728   {
729     fprintf (stderr, "Failed to setuid: %s\n", strerror (errno));
730     global_ret = 2;
731     goto cleanup;
732   }
733 #endif
734
735   if (SIG_ERR == signal (SIGPIPE, SIG_IGN))
736   {
737     fprintf (stderr, "Failed to protect against SIGPIPE: %s\n",
738              strerror (errno));
739     /* no exit, we might as well die with SIGPIPE should it ever happen */
740   }
741   run (fd_tun);
742   global_ret = 0;
743  cleanup:
744   close (fd_tun);
745   return global_ret;
746 }
747
748 /* end of gnunet-helper-exit.c */