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