Add missing file
[oweals/gnunet.git] / src / nat / gnunet-helper-nat-server.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2010 Christian Grothoff (and other contributing authors)
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., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file src/nat/gnunet-helper-nat-server.c
23  * @brief Tool to help bypass NATs using ICMP method; must run as root (SUID will do)
24  *        This code will work under GNU/Linux only (or maybe BSDs, but never W32)
25  * @author Christian Grothoff
26  *
27  * This program will send ONE ICMP message every 500 ms RAW sockets
28  * to a DUMMY IP address and also listens for ICMP replies.  Since
29  * it uses RAW sockets, it must be installed SUID or run as 'root'.
30  * In order to keep the security risk of the resulting SUID binary
31  * minimal, the program ONLY opens the two RAW sockets with root
32  * privileges, then drops them and only then starts to process
33  * command line arguments.  The code also does not link against
34  * any shared libraries (except libc) and is strictly minimal
35  * (except for checking for errors).  The following list of people
36  * have reviewed this code and considered it safe since the last
37  * modification (if you reviewed it, please have your name added
38  * to the list):
39  *
40  * - Christian Grothoff
41  * - Nathan Evans
42  * - Benjamin Kuperman (22 Aug 2010)
43  * - Jacob Appelbaum (19 Dec 2011)
44  */
45 #if HAVE_CONFIG_H
46 /* Just needed for HAVE_SOCKADDR_IN_SIN_LEN test macro! */
47 #include "gnunet_config.h"
48 #else
49 #define _GNU_SOURCE
50 #endif
51 #include <sys/types.h>
52 #include <sys/socket.h>
53 #include <arpa/inet.h>
54 #include <sys/select.h>
55 #include <sys/time.h>
56 #include <sys/types.h>
57 #include <unistd.h>
58 #include <stdio.h>
59 #include <string.h>
60 #include <errno.h>
61 #include <stdlib.h>
62 #include <stdint.h>
63 #include <time.h>
64 #include <netinet/ip.h>
65 #include <netinet/ip_icmp.h>
66 #include <netinet/in.h>
67
68 /* The following constant is missing from FreeBSD 9.2 */
69 #ifndef ICMP_TIME_EXCEEDED
70 #define ICMP_TIME_EXCEEDED 11
71 #endif
72
73 /**
74  * Should we print some debug output?
75  */
76 #define VERBOSE 0
77
78 /**
79  * Must match packet ID used by gnunet-helper-nat-client.c
80  */
81 #define PACKET_ID 256
82
83 /**
84  * Must match IP given in the client.
85  */
86 #define DUMMY_IP "192.0.2.86"
87
88 /**
89  * Port for UDP
90  */
91 #define NAT_TRAV_PORT 22225
92
93 /**
94  * How often do we send our ICMP messages to receive replies?
95  */
96 #define ICMP_SEND_FREQUENCY_MS 500
97
98 /**
99  * IPv4 header.
100  */
101 struct ip_header
102 {
103
104   /**
105    * Version (4 bits) + Internet header length (4 bits)
106    */
107   uint8_t vers_ihl;
108
109   /**
110    * Type of service
111    */
112   uint8_t tos;
113
114   /**
115    * Total length
116    */
117   uint16_t pkt_len;
118
119   /**
120    * Identification
121    */
122   uint16_t id;
123
124   /**
125    * Flags (3 bits) + Fragment offset (13 bits)
126    */
127   uint16_t flags_frag_offset;
128
129   /**
130    * Time to live
131    */
132   uint8_t ttl;
133
134   /**
135    * Protocol
136    */
137   uint8_t proto;
138
139   /**
140    * Header checksum
141    */
142   uint16_t checksum;
143
144   /**
145    * Source address
146    */
147   uint32_t src_ip;
148
149   /**
150    * Destination address
151    */
152   uint32_t dst_ip;
153 };
154
155 /**
156  * Format of ICMP packet.
157  */
158 struct icmp_ttl_exceeded_header
159 {
160   uint8_t type;
161
162   uint8_t code;
163
164   uint16_t checksum;
165
166   uint32_t unused;
167
168   /* followed by original payload */
169 };
170
171 struct icmp_echo_header
172 {
173   uint8_t type;
174
175   uint8_t code;
176
177   uint16_t checksum;
178
179   uint32_t reserved;
180 };
181
182
183 /**
184  * Beginning of UDP packet.
185  */
186 struct udp_header
187 {
188   uint16_t src_port;
189
190   uint16_t dst_port;
191
192   uint16_t length;
193
194   uint16_t crc;
195 };
196
197 /**
198  * Socket we use to receive "fake" ICMP replies.
199  */
200 static int icmpsock;
201
202 /**
203  * Socket we use to send our ICMP requests.
204  */
205 static int rawsock;
206
207 /**
208  * Socket we use to send our UDP requests.
209  */
210 static int udpsock;
211
212 /**
213  * Target "dummy" address.
214  */
215 static struct in_addr dummy;
216
217
218 /**
219  * CRC-16 for IP/ICMP headers.
220  *
221  * @param data what to calculate the CRC over
222  * @param bytes number of bytes in data (must be multiple of 2)
223  * @return the CRC 16.
224  */
225 static uint16_t
226 calc_checksum (const uint16_t * data, unsigned int bytes)
227 {
228   uint32_t sum;
229   unsigned int i;
230
231   sum = 0;
232   for (i = 0; i < bytes / 2; i++)
233     sum += data[i];
234   sum = (sum & 0xffff) + (sum >> 16);
235   sum = htons (0xffff - sum);
236   return sum;
237 }
238
239
240 /**
241  * Send an ICMP message to the dummy IP.
242  *
243  * @param my_ip source address (our ip address)
244  */
245 static void
246 send_icmp_echo (const struct in_addr *my_ip)
247 {
248   char packet[sizeof (struct ip_header) + sizeof (struct icmp_echo_header)];
249   struct icmp_echo_header icmp_echo;
250   struct ip_header ip_pkt;
251   struct sockaddr_in dst;
252   size_t off;
253   int err;
254
255   off = 0;
256   ip_pkt.vers_ihl = 0x45;
257   ip_pkt.tos = 0;
258   ip_pkt.pkt_len = htons (sizeof (packet));
259   ip_pkt.id = htons (PACKET_ID);
260   ip_pkt.flags_frag_offset = 0;
261   ip_pkt.ttl = IPDEFTTL;
262   ip_pkt.proto = IPPROTO_ICMP;
263   ip_pkt.checksum = 0;
264   ip_pkt.src_ip = my_ip->s_addr;
265   ip_pkt.dst_ip = dummy.s_addr;
266   ip_pkt.checksum =
267       htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header)));
268   memcpy (&packet[off], &ip_pkt, sizeof (struct ip_header));
269   off += sizeof (struct ip_header);
270
271   icmp_echo.type = ICMP_ECHO;
272   icmp_echo.code = 0;
273   icmp_echo.checksum = 0;
274   icmp_echo.reserved = 0;
275   icmp_echo.checksum =
276       htons (calc_checksum
277              ((uint16_t *) & icmp_echo, sizeof (struct icmp_echo_header)));
278   memcpy (&packet[off], &icmp_echo, sizeof (struct icmp_echo_header));
279   off += sizeof (struct icmp_echo_header);
280
281   memset (&dst, 0, sizeof (dst));
282   dst.sin_family = AF_INET;
283 #if HAVE_SOCKADDR_IN_SIN_LEN
284   dst.sin_len = sizeof (struct sockaddr_in);
285 #endif
286   dst.sin_addr = dummy;
287   err =
288       sendto (rawsock, packet, off, 0, (struct sockaddr *) &dst, sizeof (dst));
289   if (err < 0)
290   {
291 #if VERBOSE
292     fprintf (stderr, "sendto failed: %s\n", strerror (errno));
293 #endif
294   }
295   else if (sizeof (packet) != err)
296   {
297     fprintf (stderr, "Error: partial send of ICMP message\n");
298   }
299 }
300
301
302 /**
303  * Send a UDP message to the dummy IP.
304  */
305 static void
306 send_udp ()
307 {
308   struct sockaddr_in dst;
309   ssize_t err;
310
311   memset (&dst, 0, sizeof (dst));
312   dst.sin_family = AF_INET;
313 #if HAVE_SOCKADDR_IN_SIN_LEN
314   dst.sin_len = sizeof (struct sockaddr_in);
315 #endif
316   dst.sin_addr = dummy;
317   dst.sin_port = htons (NAT_TRAV_PORT);
318   err = sendto (udpsock, NULL, 0, 0, (struct sockaddr *) &dst, sizeof (dst));
319   if (err < 0)
320   {
321 #if VERBOSE
322     fprintf (stderr, "sendto failed: %s\n", strerror (errno));
323 #endif
324   }
325   else if (0 != err)
326   {
327     fprintf (stderr, "Error: partial send of ICMP message\n");
328   }
329 }
330
331
332 /**
333  * We've received an ICMP response.  Process it.
334  */
335 static void
336 process_icmp_response ()
337 {
338   char buf[65536];
339   ssize_t have;
340   struct in_addr source_ip;
341   struct ip_header ip_pkt;
342   struct icmp_ttl_exceeded_header icmp_ttl;
343   struct icmp_echo_header icmp_echo;
344   struct udp_header udp_pkt;
345   size_t off;
346   uint16_t port;
347
348   have = read (icmpsock, buf, sizeof (buf));
349   if (-1 == have)
350   {
351     fprintf (stderr, "Error reading raw socket: %s\n", strerror (errno));
352     return;
353   }
354 #if VERBOSE
355   fprintf (stderr, "Received message of %u bytes\n", (unsigned int) have);
356 #endif
357   if (have <
358       (ssize_t) (sizeof (struct ip_header) +
359                  sizeof (struct icmp_ttl_exceeded_header) +
360                  sizeof (struct ip_header)))
361   {
362     /* malformed */
363     return;
364   }
365   off = 0;
366   memcpy (&ip_pkt, &buf[off], sizeof (struct ip_header));
367   off += sizeof (struct ip_header);
368   memcpy (&icmp_ttl, &buf[off], sizeof (struct icmp_ttl_exceeded_header));
369   off += sizeof (struct icmp_ttl_exceeded_header);
370   if ((ICMP_TIME_EXCEEDED != icmp_ttl.type) || (0 != icmp_ttl.code))
371   {
372     /* different type than what we want */
373     return;
374   }
375   /* grab source IP of 1st IP header */
376   source_ip.s_addr = ip_pkt.src_ip;
377
378   /* skip 2nd IP header */
379   memcpy (&ip_pkt, &buf[off], sizeof (struct ip_header));
380   off += sizeof (struct ip_header);
381
382   switch (ip_pkt.proto)
383   {
384   case IPPROTO_ICMP:
385     if (have !=
386         (sizeof (struct ip_header) * 2 +
387          sizeof (struct icmp_ttl_exceeded_header) +
388          sizeof (struct icmp_echo_header)))
389     {
390       /* malformed */
391       return;
392     }
393     /* grab ICMP ECHO content */
394     memcpy (&icmp_echo, &buf[off], sizeof (struct icmp_echo_header));
395     port = (uint16_t) ntohl (icmp_echo.reserved);
396     break;
397   case IPPROTO_UDP:
398     if (have !=
399         (sizeof (struct ip_header) * 2 +
400          sizeof (struct icmp_ttl_exceeded_header) + sizeof (struct udp_header)))
401     {
402       /* malformed */
403       return;
404     }
405     /* grab UDP content */
406     memcpy (&udp_pkt, &buf[off], sizeof (struct udp_header));
407     port = ntohs (udp_pkt.length);
408     break;
409   default:
410     /* different type than what we want */
411     return;
412   }
413
414   if (port == 0)
415     fprintf (stdout, "%s\n",
416              inet_ntop (AF_INET, &source_ip, buf, sizeof (buf)));
417   else
418     fprintf (stdout, "%s:%u\n",
419              inet_ntop (AF_INET, &source_ip, buf, sizeof (buf)),
420              (unsigned int) port);
421   fflush (stdout);
422 }
423
424
425 /**
426  * Fully initialize the raw socket.
427  *
428  * @return -1 on error, 0 on success
429  */
430 static int
431 setup_raw_socket ()
432 {
433   const int one = 1;
434
435   if (-1 ==
436       setsockopt (rawsock, SOL_SOCKET, SO_BROADCAST, (char *) &one, sizeof (one)))
437   {
438     fprintf (stderr, "setsockopt failed: %s\n", strerror (errno));
439     return -1;
440   }
441   if (-1 ==
442       setsockopt (rawsock, IPPROTO_IP, IP_HDRINCL, (char *) &one, sizeof (one)))
443   {
444     fprintf (stderr, "setsockopt failed: %s\n", strerror (errno));
445     return -1;
446   }
447   return 0;
448 }
449
450
451 /**
452  * Create a UDP socket for writing.
453  *
454  * @param my_ip source address (our ip address)
455  * @return -1 on error
456  */
457 static int
458 make_udp_socket (const struct in_addr *my_ip)
459 {
460   int ret;
461   struct sockaddr_in addr;
462
463   ret = socket (AF_INET, SOCK_DGRAM, 0);
464   if (-1 == ret)
465   {
466     fprintf (stderr,
467              "Error opening UDP socket: %s\n",
468              strerror (errno));
469     return -1;
470   }
471   memset (&addr, 0, sizeof (addr));
472   addr.sin_family = AF_INET;
473 #if HAVE_SOCKADDR_IN_SIN_LEN
474   addr.sin_len = sizeof (struct sockaddr_in);
475 #endif
476   addr.sin_addr = *my_ip;
477   addr.sin_port = htons (NAT_TRAV_PORT);
478
479   if (0 != bind (ret,
480                  (struct sockaddr *) &addr,
481                  sizeof (addr)))
482   {
483     fprintf (stderr,
484              "Error binding UDP socket to port %u: %s\n",
485              NAT_TRAV_PORT,
486              strerror (errno));
487     (void) close (ret);
488     return -1;
489   }
490   return ret;
491 }
492
493
494 int
495 main (int argc, char *const *argv)
496 {
497   struct in_addr external;
498   fd_set rs;
499   struct timeval tv;
500   uid_t uid;
501   unsigned int alt;
502   int icmp_eno;
503   int raw_eno;
504   int global_ret;
505
506   /* Create an ICMP raw socket for reading (we'll check errors later) */
507   icmpsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
508   icmp_eno = errno;
509
510   /* Create an (ICMP) raw socket for writing (we'll check errors later) */
511   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
512   raw_eno = errno;
513   udpsock = -1;
514
515   /* drop root rights */
516   uid = getuid ();
517 #ifdef HAVE_SETRESUID
518   if (0 != setresuid (uid, uid, uid))
519   {
520     fprintf (stderr, "Failed to setresuid: %s\n", strerror (errno));
521     global_ret = 1;
522     goto error_exit;
523   }
524 #else
525   if (0 != (setuid (uid) | seteuid (uid)))
526   {
527     fprintf (stderr, "Failed to setuid: %s\n", strerror (errno));
528     global_ret = 2;
529     goto error_exit;
530   }
531 #endif
532
533   /* Now that we run without root rights, we can do error checking... */
534   if (2 != argc)
535   {
536     fprintf (stderr,
537              "This program must be started with our (internal NAT) IP as the only argument.\n");
538     global_ret = 3;
539     goto error_exit;
540   }
541   if (1 != inet_pton (AF_INET, argv[1], &external))
542   {
543     fprintf (stderr, "Error parsing IPv4 address: %s\n", strerror (errno));
544     global_ret = 4;
545     goto error_exit;
546   }
547   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy))
548   {
549     fprintf (stderr, "Internal error converting dummy IP to binary.\n");
550     global_ret = 5;
551     goto error_exit;
552   }
553
554   /* error checking icmpsock */
555   if (-1 == icmpsock)
556   {
557     fprintf (stderr, "Error opening RAW socket: %s\n", strerror (icmp_eno));
558     global_ret = 6;
559     goto error_exit;
560   }
561   if (icmpsock >= FD_SETSIZE)
562   {
563     /* this could happen if we were started with a large number of already-open
564        file descriptors... */
565     fprintf (stderr, "Socket number too large (%d > %u)\n", icmpsock,
566              (unsigned int) FD_SETSIZE);
567     global_ret = 7;
568     goto error_exit;
569   }
570
571   /* error checking rawsock */
572   if (-1 == rawsock)
573   {
574     fprintf (stderr, "Error opening RAW socket: %s\n", strerror (raw_eno));
575     global_ret = 8;
576     goto error_exit;
577   }
578   /* no need to check 'rawsock' against FD_SETSIZE as it is never used
579      with 'select' */
580
581   if (0 != setup_raw_socket ())
582   {
583     global_ret = 9;
584     goto error_exit;
585   }
586
587   if (-1 == (udpsock = make_udp_socket (&external)))
588   {
589     global_ret = 10;
590     goto error_exit;
591   }
592
593   alt = 0;
594   while (1)
595   {
596     FD_ZERO (&rs);
597     FD_SET (icmpsock, &rs);
598     tv.tv_sec = 0;
599     tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000;
600     if (-1 == select (icmpsock + 1, &rs, NULL, NULL, &tv))
601     {
602       if (errno == EINTR)
603         continue;
604       fprintf (stderr, "select failed: %s\n", strerror (errno));
605       break;
606     }
607     if (1 == getppid ())        /* Check the parent process id, if 1 the parent has died, so we should die too */
608       break;
609     if (FD_ISSET (icmpsock, &rs))
610       process_icmp_response ();
611     if (0 == (++alt % 2))
612       send_icmp_echo (&external);
613     else
614       send_udp ();
615   }
616
617   /* select failed (internal error or OS out of resources) */
618   global_ret = 11;
619 error_exit:
620   if (-1 != icmpsock)
621     (void) close (icmpsock);
622   if (-1 != rawsock)
623     (void) close (rawsock);
624   if (-1 != udpsock)
625     (void) close (udpsock);
626   return global_ret;
627 }
628
629
630 /* end of gnunet-helper-nat-server.c */