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