indentation
[oweals/gnunet.git] / src / nat / gnunet-helper-nat-server.c
1 /*
2      This file is part of GNUnet.
3      (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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, 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  */
44 #if HAVE_CONFIG_H
45 /* Just needed for HAVE_SOCKADDR_IN_SIN_LEN test macro! */
46 #include "gnunet_config.h"
47 #else
48 #define _GNU_SOURCE
49 #endif
50 #include <sys/types.h>
51 #include <sys/socket.h>
52 #include <arpa/inet.h>
53 #include <sys/select.h>
54 #include <sys/time.h>
55 #include <sys/types.h>
56 #include <unistd.h>
57 #include <stdio.h>
58 #include <string.h>
59 #include <errno.h>
60 #include <stdlib.h>
61 #include <stdint.h>
62 #include <time.h>
63 #include <netinet/ip.h>
64 #include <netinet/ip_icmp.h>
65 #include <netinet/in.h>
66
67 /**
68  * Should we print some debug output?
69  */
70 #define VERBOSE 0
71
72 /**
73  * Must match IP given in the client.
74  */
75 #define DUMMY_IP "192.0.2.86"
76
77 /**
78  * Port for UDP
79  */
80 #define NAT_TRAV_PORT 22225
81
82 /**
83  * How often do we send our ICMP messages to receive replies?
84  */
85 #define ICMP_SEND_FREQUENCY_MS 500
86
87 /**
88  * IPv4 header.
89  */
90 struct ip_header
91 {
92
93   /**
94    * Version (4 bits) + Internet header length (4 bits)
95    */
96   uint8_t vers_ihl;
97
98   /**
99    * Type of service
100    */
101   uint8_t tos;
102
103   /**
104    * Total length
105    */
106   uint16_t pkt_len;
107
108   /**
109    * Identification
110    */
111   uint16_t id;
112
113   /**
114    * Flags (3 bits) + Fragment offset (13 bits)
115    */
116   uint16_t flags_frag_offset;
117
118   /**
119    * Time to live
120    */
121   uint8_t ttl;
122
123   /**
124    * Protocol
125    */
126   uint8_t proto;
127
128   /**
129    * Header checksum
130    */
131   uint16_t checksum;
132
133   /**
134    * Source address
135    */
136   uint32_t src_ip;
137
138   /**
139    * Destination address
140    */
141   uint32_t dst_ip;
142 };
143
144 /**
145  * Format of ICMP packet.
146  */
147 struct icmp_ttl_exceeded_header
148 {
149   uint8_t type;
150
151   uint8_t code;
152
153   uint16_t checksum;
154
155   uint32_t unused;
156
157   /* followed by original payload */
158 };
159
160 struct icmp_echo_header
161 {
162   uint8_t type;
163
164   uint8_t code;
165
166   uint16_t checksum;
167
168   uint32_t reserved;
169 };
170
171
172 /**
173  * Beginning of UDP packet.
174  */
175 struct udp_header
176 {
177   uint16_t src_port;
178
179   uint16_t dst_port;
180
181   uint16_t length;
182
183   uint16_t crc;
184 };
185
186 /**
187  * Socket we use to receive "fake" ICMP replies.
188  */
189 static int icmpsock;
190
191 /**
192  * Socket we use to send our ICMP requests.
193  */
194 static int rawsock;
195
196 /**
197  * Socket we use to send our UDP requests.
198  */
199 static int udpsock;
200
201 /**
202  * Target "dummy" address.
203  */
204 static struct in_addr dummy;
205
206
207 /**
208  * CRC-16 for IP/ICMP headers.
209  *
210  * @param data what to calculate the CRC over
211  * @param bytes number of bytes in data (must be multiple of 2)
212  * @return the CRC 16.
213  */
214 static uint16_t
215 calc_checksum (const uint16_t * data, unsigned int bytes)
216 {
217   uint32_t sum;
218   unsigned int i;
219
220   sum = 0;
221   for (i = 0; i < bytes / 2; i++)
222     sum += data[i];
223   sum = (sum & 0xffff) + (sum >> 16);
224   sum = htons (0xffff - sum);
225   return sum;
226 }
227
228
229 /**
230  * Send an ICMP message to the dummy IP.
231  *
232  * @param my_ip source address (our ip address)
233  */
234 static void
235 send_icmp_echo (const struct in_addr *my_ip)
236 {
237   char packet[sizeof (struct ip_header) + sizeof (struct icmp_echo_header)];
238   struct icmp_echo_header icmp_echo;
239   struct ip_header ip_pkt;
240   struct sockaddr_in dst;
241   size_t off;
242   int err;
243
244   off = 0;
245   ip_pkt.vers_ihl = 0x45;
246   ip_pkt.tos = 0;
247   ip_pkt.pkt_len = htons (sizeof (packet));
248   ip_pkt.id = htons (256);
249   ip_pkt.flags_frag_offset = 0;
250   ip_pkt.ttl = IPDEFTTL;
251   ip_pkt.proto = IPPROTO_ICMP;
252   ip_pkt.checksum = 0;
253   ip_pkt.src_ip = my_ip->s_addr;
254   ip_pkt.dst_ip = dummy.s_addr;
255   ip_pkt.checksum = htons (calc_checksum ((uint16_t *) & ip_pkt,
256                                           sizeof (struct ip_header)));
257   memcpy (&packet[off], &ip_pkt, sizeof (struct ip_header));
258   off += sizeof (struct ip_header);
259
260   icmp_echo.type = ICMP_ECHO;
261   icmp_echo.code = 0;
262   icmp_echo.checksum = 0;
263   icmp_echo.reserved = 0;
264   icmp_echo.checksum = htons (calc_checksum ((uint16_t *) & icmp_echo,
265                                              sizeof (struct icmp_echo_header)));
266   memcpy (&packet[off], &icmp_echo, sizeof (struct icmp_echo_header));
267   off += sizeof (struct icmp_echo_header);
268
269   memset (&dst, 0, sizeof (dst));
270   dst.sin_family = AF_INET;
271 #if HAVE_SOCKADDR_IN_SIN_LEN
272   dst.sin_len = sizeof (struct sockaddr_in);
273 #endif
274   dst.sin_addr = dummy;
275   err = sendto (rawsock,
276                 packet, off, 0, (struct sockaddr *) &dst, sizeof (dst));
277   if (err < 0)
278   {
279 #if VERBOSE
280     fprintf (stderr, "sendto failed: %s\n", strerror (errno));
281 #endif
282   }
283   else if (sizeof (packet) != err)
284   {
285     fprintf (stderr, "Error: partial send of ICMP message\n");
286   }
287 }
288
289
290 /**
291  * Send a UDP message to the dummy IP.
292  */
293 static void
294 send_udp ()
295 {
296   struct sockaddr_in dst;
297   ssize_t err;
298
299   memset (&dst, 0, sizeof (dst));
300   dst.sin_family = AF_INET;
301 #if HAVE_SOCKADDR_IN_SIN_LEN
302   dst.sin_len = sizeof (struct sockaddr_in);
303 #endif
304   dst.sin_addr = dummy;
305   dst.sin_port = htons (NAT_TRAV_PORT);
306   err = sendto (udpsock, NULL, 0, 0, (struct sockaddr *) &dst, sizeof (dst));
307   if (err < 0)
308   {
309 #if VERBOSE
310     fprintf (stderr, "sendto failed: %s\n", strerror (errno));
311 #endif
312   }
313   else if (0 != err)
314   {
315     fprintf (stderr, "Error: partial send of ICMP message\n");
316   }
317 }
318
319
320 /**
321  * We've received an ICMP response.  Process it.
322  */
323 static void
324 process_icmp_response ()
325 {
326   char buf[65536];
327   ssize_t have;
328   struct in_addr source_ip;
329   struct ip_header ip_pkt;
330   struct icmp_ttl_exceeded_header icmp_ttl;
331   struct icmp_echo_header icmp_echo;
332   struct udp_header udp_pkt;
333   size_t off;
334   uint16_t port;
335
336   have = read (icmpsock, buf, sizeof (buf));
337   if (-1 == have)
338   {
339     fprintf (stderr, "Error reading raw socket: %s\n", strerror (errno));
340     return;
341   }
342 #if VERBOSE
343   fprintf (stderr, "Received message of %u bytes\n", (unsigned int) have);
344 #endif
345   if (have <
346       (ssize_t) (sizeof (struct ip_header) +
347                  sizeof (struct icmp_ttl_exceeded_header) +
348                  sizeof (struct ip_header)))
349   {
350     /* malformed */
351     return;
352   }
353   off = 0;
354   memcpy (&ip_pkt, &buf[off], sizeof (struct ip_header));
355   off += sizeof (struct ip_header);
356   memcpy (&source_ip, &ip_pkt.src_ip, sizeof (source_ip));
357   memcpy (&icmp_ttl, &buf[off], sizeof (struct icmp_ttl_exceeded_header));
358   off += sizeof (struct icmp_ttl_exceeded_header);
359   if ((ICMP_TIME_EXCEEDED != icmp_ttl.type) || (0 != icmp_ttl.code))
360   {
361     /* different type than what we want */
362     return;
363   }
364   /* skip 2nd IP header */
365   memcpy (&ip_pkt, &buf[off], sizeof (struct ip_header));
366   off += sizeof (struct ip_header);
367
368   switch (ip_pkt.proto)
369   {
370   case IPPROTO_ICMP:
371     if (have != (sizeof (struct ip_header) * 2 +
372                  sizeof (struct icmp_ttl_exceeded_header) +
373                  sizeof (struct icmp_echo_header)))
374     {
375       /* malformed */
376       return;
377     }
378     /* grab ICMP ECHO content */
379     memcpy (&icmp_echo, &buf[off], sizeof (struct icmp_echo_header));
380     port = (uint16_t) ntohl (icmp_echo.reserved);
381     break;
382   case IPPROTO_UDP:
383     if (have != (sizeof (struct ip_header) * 2 +
384                  sizeof (struct icmp_ttl_exceeded_header) +
385                  sizeof (struct udp_header)))
386     {
387       /* malformed */
388       return;
389     }
390     /* grab UDP content */
391     memcpy (&udp_pkt, &buf[off], sizeof (struct udp_header));
392     port = ntohs (udp_pkt.length);
393     break;
394   default:
395     /* different type than what we want */
396     return;
397   }
398
399   if (port == 0)
400     fprintf (stdout,
401              "%s\n", inet_ntop (AF_INET, &source_ip, buf, sizeof (buf)));
402   else
403     fprintf (stdout,
404              "%s:%u\n",
405              inet_ntop (AF_INET,
406                         &source_ip, buf, sizeof (buf)), (unsigned int) port);
407   fflush (stdout);
408 }
409
410
411 /**
412  * Create an ICMP raw socket for reading.
413  *
414  * @return -1 on error
415  */
416 static int
417 make_icmp_socket ()
418 {
419   int ret;
420
421   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
422   if (-1 == ret)
423   {
424     fprintf (stderr, "Error opening RAW socket: %s\n", strerror (errno));
425     return -1;
426   }
427   if (ret >= FD_SETSIZE)
428   {
429     fprintf (stderr,
430              "Socket number too large (%d > %u)\n",
431              ret, (unsigned int) FD_SETSIZE);
432     close (ret);
433     return -1;
434   }
435   return ret;
436 }
437
438
439 /**
440  * Create an ICMP raw socket for writing.
441  *
442  * @return -1 on error
443  */
444 static int
445 make_raw_socket ()
446 {
447   const int one = 1;
448   int ret;
449
450   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
451   if (-1 == ret)
452   {
453     fprintf (stderr, "Error opening RAW socket: %s\n", strerror (errno));
454     return -1;
455   }
456   if (-1 == setsockopt (ret,
457                         SOL_SOCKET, SO_BROADCAST, (char *) &one, sizeof (one)))
458   {
459     fprintf (stderr, "setsockopt failed: %s\n", strerror (errno));
460     close (ret);
461     return -1;
462   }
463   if (-1 == setsockopt (ret,
464                         IPPROTO_IP, IP_HDRINCL, (char *) &one, sizeof (one)))
465   {
466     fprintf (stderr, "setsockopt failed: %s\n", strerror (errno));
467     close (ret);
468     return -1;
469   }
470   return ret;
471 }
472
473
474 /**
475  * Create a UDP socket for writinging.
476  *
477  * @param my_ip source address (our ip address)
478  * @return -1 on error
479  */
480 static int
481 make_udp_socket (const struct in_addr *my_ip)
482 {
483   int ret;
484   struct sockaddr_in addr;
485
486   ret = socket (AF_INET, SOCK_DGRAM, 0);
487   if (-1 == ret)
488   {
489     fprintf (stderr, "Error opening UDP socket: %s\n", strerror (errno));
490     return -1;
491   }
492   memset (&addr, 0, sizeof (addr));
493   addr.sin_family = AF_INET;
494 #if HAVE_SOCKADDR_IN_SIN_LEN
495   addr.sin_len = sizeof (struct sockaddr_in);
496 #endif
497   addr.sin_addr = *my_ip;
498   addr.sin_port = htons (NAT_TRAV_PORT);
499
500   if (0 != bind (ret, &addr, sizeof (addr)))
501   {
502     fprintf (stderr,
503              "Error binding UDP socket to port %u: %s\n",
504              NAT_TRAV_PORT, strerror (errno));
505     /* likely problematic, but not certain, try to continue */
506   }
507   return ret;
508 }
509
510
511 int
512 main (int argc, char *const *argv)
513 {
514   struct in_addr external;
515   fd_set rs;
516   struct timeval tv;
517   uid_t uid;
518   unsigned int alt;
519
520   if (2 != argc)
521   {
522     fprintf (stderr,
523              "This program must be started with our (internal NAT) IP as the only argument.\n");
524     return 1;
525   }
526   if (1 != inet_pton (AF_INET, argv[1], &external))
527   {
528     fprintf (stderr, "Error parsing IPv4 address: %s\n", strerror (errno));
529     return 1;
530   }
531   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy))
532   {
533     fprintf (stderr, "Internal error converting dummy IP to binary.\n");
534     return 2;
535   }
536   if (-1 == (icmpsock = make_icmp_socket ()))
537   {
538     return 3;
539   }
540   if (-1 == (rawsock = make_raw_socket ()))
541   {
542     close (icmpsock);
543     return 3;
544   }
545   uid = getuid ();
546   if (0 != setresuid (uid, uid, uid))
547   {
548     fprintf (stderr, "Failed to setresuid: %s\n", strerror (errno));
549     /* not critical, continue anyway */
550   }
551   if (-1 == (udpsock = make_udp_socket (&external)))
552   {
553     close (icmpsock);
554     close (rawsock);
555     return 3;
556   }
557   alt = 0;
558   while (1)
559   {
560     FD_ZERO (&rs);
561     FD_SET (icmpsock, &rs);
562     tv.tv_sec = 0;
563     tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000;
564     if (-1 == select (icmpsock + 1, &rs, NULL, NULL, &tv))
565     {
566       if (errno == EINTR)
567         continue;
568       fprintf (stderr, "select failed: %s\n", strerror (errno));
569       break;
570     }
571     if (1 == getppid ())        /* Check the parent process id, if 1 the parent has died, so we should die too */
572       break;
573     if (FD_ISSET (icmpsock, &rs))
574       process_icmp_response ();
575     if (0 == (++alt % 2))
576       send_icmp_echo (&external);
577     else
578       send_udp ();
579   }
580   /* select failed (internal error or OS out of resources) */
581   close (icmpsock);
582   close (rawsock);
583   close (udpsock);
584   return 4;
585 }
586
587
588 /* end of gnunet-helper-nat-server.c */