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