disable local addresses
[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 =
256       htons (calc_checksum ((uint16_t *) & ip_pkt, 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 =
265       htons (calc_checksum
266              ((uint16_t *) & icmp_echo, sizeof (struct icmp_echo_header)));
267   memcpy (&packet[off], &icmp_echo, sizeof (struct icmp_echo_header));
268   off += sizeof (struct icmp_echo_header);
269
270   memset (&dst, 0, sizeof (dst));
271   dst.sin_family = AF_INET;
272 #if HAVE_SOCKADDR_IN_SIN_LEN
273   dst.sin_len = sizeof (struct sockaddr_in);
274 #endif
275   dst.sin_addr = dummy;
276   err =
277       sendto (rawsock, packet, off, 0, (struct sockaddr *) &dst, sizeof (dst));
278   if (err < 0)
279   {
280 #if VERBOSE
281     fprintf (stderr, "sendto failed: %s\n", strerror (errno));
282 #endif
283   }
284   else if (sizeof (packet) != err)
285   {
286     fprintf (stderr, "Error: partial send of ICMP message\n");
287   }
288 }
289
290
291 /**
292  * Send a UDP message to the dummy IP.
293  */
294 static void
295 send_udp ()
296 {
297   struct sockaddr_in dst;
298   ssize_t err;
299
300   memset (&dst, 0, sizeof (dst));
301   dst.sin_family = AF_INET;
302 #if HAVE_SOCKADDR_IN_SIN_LEN
303   dst.sin_len = sizeof (struct sockaddr_in);
304 #endif
305   dst.sin_addr = dummy;
306   dst.sin_port = htons (NAT_TRAV_PORT);
307   err = sendto (udpsock, NULL, 0, 0, (struct sockaddr *) &dst, sizeof (dst));
308   if (err < 0)
309   {
310 #if VERBOSE
311     fprintf (stderr, "sendto failed: %s\n", strerror (errno));
312 #endif
313   }
314   else if (0 != err)
315   {
316     fprintf (stderr, "Error: partial send of ICMP message\n");
317   }
318 }
319
320
321 /**
322  * We've received an ICMP response.  Process it.
323  */
324 static void
325 process_icmp_response ()
326 {
327   char buf[65536];
328   ssize_t have;
329   struct in_addr source_ip;
330   struct ip_header ip_pkt;
331   struct icmp_ttl_exceeded_header icmp_ttl;
332   struct icmp_echo_header icmp_echo;
333   struct udp_header udp_pkt;
334   size_t off;
335   uint16_t port;
336
337   have = read (icmpsock, buf, sizeof (buf));
338   if (-1 == have)
339   {
340     fprintf (stderr, "Error reading raw socket: %s\n", strerror (errno));
341     return;
342   }
343 #if VERBOSE
344   fprintf (stderr, "Received message of %u bytes\n", (unsigned int) have);
345 #endif
346   if (have <
347       (ssize_t) (sizeof (struct ip_header) +
348                  sizeof (struct icmp_ttl_exceeded_header) +
349                  sizeof (struct ip_header)))
350   {
351     /* malformed */
352     return;
353   }
354   off = 0;
355   memcpy (&ip_pkt, &buf[off], sizeof (struct ip_header));
356   off += sizeof (struct ip_header);
357   memcpy (&source_ip, &ip_pkt.src_ip, sizeof (source_ip));
358   memcpy (&icmp_ttl, &buf[off], sizeof (struct icmp_ttl_exceeded_header));
359   off += sizeof (struct icmp_ttl_exceeded_header);
360   if ((ICMP_TIME_EXCEEDED != icmp_ttl.type) || (0 != icmp_ttl.code))
361   {
362     /* different type than what we want */
363     return;
364   }
365   /* skip 2nd IP header */
366   memcpy (&ip_pkt, &buf[off], sizeof (struct ip_header));
367   off += sizeof (struct ip_header);
368
369   switch (ip_pkt.proto)
370   {
371   case IPPROTO_ICMP:
372     if (have !=
373         (sizeof (struct ip_header) * 2 +
374          sizeof (struct icmp_ttl_exceeded_header) +
375          sizeof (struct icmp_echo_header)))
376     {
377       /* malformed */
378       return;
379     }
380     /* grab ICMP ECHO content */
381     memcpy (&icmp_echo, &buf[off], sizeof (struct icmp_echo_header));
382     port = (uint16_t) ntohl (icmp_echo.reserved);
383     break;
384   case IPPROTO_UDP:
385     if (have !=
386         (sizeof (struct ip_header) * 2 +
387          sizeof (struct icmp_ttl_exceeded_header) + sizeof (struct udp_header)))
388     {
389       /* malformed */
390       return;
391     }
392     /* grab UDP content */
393     memcpy (&udp_pkt, &buf[off], sizeof (struct udp_header));
394     port = ntohs (udp_pkt.length);
395     break;
396   default:
397     /* different type than what we want */
398     return;
399   }
400
401   if (port == 0)
402     fprintf (stdout, "%s\n",
403              inet_ntop (AF_INET, &source_ip, buf, sizeof (buf)));
404   else
405     fprintf (stdout, "%s:%u\n",
406              inet_ntop (AF_INET, &source_ip, buf, sizeof (buf)),
407              (unsigned int) port);
408   fflush (stdout);
409 }
410
411
412 /**
413  * Create an ICMP raw socket for reading.
414  *
415  * @return -1 on error
416  */
417 static int
418 make_icmp_socket ()
419 {
420   int ret;
421
422   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
423   if (-1 == ret)
424   {
425     fprintf (stderr, "Error opening RAW socket: %s\n", strerror (errno));
426     return -1;
427   }
428   if (ret >= FD_SETSIZE)
429   {
430     fprintf (stderr, "Socket number too large (%d > %u)\n", ret,
431              (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 ==
457       setsockopt (ret, 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 ==
464       setsockopt (ret, 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, "Error binding UDP socket to port %u: %s\n", NAT_TRAV_PORT,
503              strerror (errno));
504     /* likely problematic, but not certain, try to continue */
505   }
506   return ret;
507 }
508
509
510 int
511 main (int argc, char *const *argv)
512 {
513   struct in_addr external;
514   fd_set rs;
515   struct timeval tv;
516   uid_t uid;
517   unsigned int alt;
518
519   if (2 != argc)
520   {
521     fprintf (stderr,
522              "This program must be started with our (internal NAT) IP as the only argument.\n");
523     return 1;
524   }
525   if (1 != inet_pton (AF_INET, argv[1], &external))
526   {
527     fprintf (stderr, "Error parsing IPv4 address: %s\n", strerror (errno));
528     return 1;
529   }
530   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy))
531   {
532     fprintf (stderr, "Internal error converting dummy IP to binary.\n");
533     return 2;
534   }
535   if (-1 == (icmpsock = make_icmp_socket ()))
536   {
537     return 3;
538   }
539   if (-1 == (rawsock = make_raw_socket ()))
540   {
541     close (icmpsock);
542     return 3;
543   }
544   uid = getuid ();
545   if (0 != setresuid (uid, uid, uid))
546   {
547     fprintf (stderr, "Failed to setresuid: %s\n", strerror (errno));
548     /* not critical, continue anyway */
549   }
550   if (-1 == (udpsock = make_udp_socket (&external)))
551   {
552     close (icmpsock);
553     close (rawsock);
554     return 3;
555   }
556   alt = 0;
557   while (1)
558   {
559     FD_ZERO (&rs);
560     FD_SET (icmpsock, &rs);
561     tv.tv_sec = 0;
562     tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000;
563     if (-1 == select (icmpsock + 1, &rs, NULL, NULL, &tv))
564     {
565       if (errno == EINTR)
566         continue;
567       fprintf (stderr, "select failed: %s\n", strerror (errno));
568       break;
569     }
570     if (1 == getppid ())        /* Check the parent process id, if 1 the parent has died, so we should die too */
571       break;
572     if (FD_ISSET (icmpsock, &rs))
573       process_icmp_response ();
574     if (0 == (++alt % 2))
575       send_icmp_echo (&external);
576     else
577       send_udp ();
578   }
579   /* select failed (internal error or OS out of resources) */
580   close (icmpsock);
581   close (rawsock);
582   close (udpsock);
583   return 4;
584 }
585
586
587 /* end of gnunet-helper-nat-server.c */