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