stuff
[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 = sizeof (packet);
248   ip_pkt.id = 1;
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(struct sockaddr_in));
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  * @param my_ip source address (our ip address)
302  */
303 static void
304 send_udp ()
305 {
306   struct sockaddr_in dst;
307   ssize_t err;
308  
309   memset (&dst, 0, sizeof (dst));
310   dst.sin_family = AF_INET;
311 #if HAVE_SOCKADDR_IN_SIN_LEN
312   dst.sin_len = sizeof (struct sockaddr_in);
313 #endif
314   dst.sin_addr = dummy;
315   dst.sin_port = htons (NAT_TRAV_PORT);
316   err = sendto(udpsock, 
317                NULL, 0, 0, 
318                (struct sockaddr*)&dst, 
319                sizeof(dst));
320   if (err < 0) 
321     {
322 #if VERBOSE
323       fprintf(stderr,
324               "sendto failed: %s\n", strerror(errno));
325 #endif
326     }
327   else if (0 != err) 
328     {
329       fprintf(stderr,
330               "Error: partial send of ICMP message\n");
331     }
332 }
333
334
335 /**
336  * We've received an ICMP response.  Process it.
337  */
338 static void
339 process_icmp_response ()
340 {
341   char buf[65536];
342   ssize_t have;
343   struct in_addr source_ip;
344   struct ip_header ip_pkt;
345   struct icmp_ttl_exceeded_header icmp_pkt;
346   struct icmp_echo_header icmp_echo_pkt;
347   struct udp_header udp_pkt;
348   size_t off;
349   uint32_t port;
350   
351   have = read (icmpsock, buf, sizeof (buf));
352   if (-1 == have)
353     {
354       fprintf (stderr,
355                "Error reading raw socket: %s\n",
356                strerror (errno));
357       return; 
358     }
359 #if VERBOSE
360   fprintf (stderr,
361            "Received message of %u bytes\n",
362            (unsigned int) have);
363 #endif
364   if (have < sizeof (struct ip_header) + sizeof (struct icmp_ttl_exceeded_header) + sizeof (struct ip_header) )
365     {
366       /* malformed */
367       return;
368     }
369   off = 0;
370   memcpy (&ip_pkt,
371           &buf[off], 
372           sizeof (struct ip_header));
373   off += sizeof (struct ip_header);
374   memcpy(&source_ip, 
375          &ip_pkt.src_ip, 
376          sizeof (source_ip));
377   memcpy (&icmp_pkt, 
378           &buf[off], 
379           sizeof (struct icmp_ttl_exceeded_header));
380   off += sizeof (struct icmp_ttl_exceeded_header);
381   if ( (ICMP_TIME_EXCEEDED != icmp_pkt.type) || 
382        (0 != icmp_pkt.code) )
383     {
384       /* different type than what we want */
385       return;
386     }
387   /* skip 2nd IP header */
388   off += sizeof (struct ip_header);
389
390   switch (ip_pkt.proto)
391     {
392     case IPPROTO_ICMP:
393       if (have != (sizeof (struct ip_header) * 2 + 
394                    sizeof (struct icmp_ttl_exceeded_header) + 
395                    sizeof (struct icmp_echo_header)) )
396         {
397           /* malformed */
398           return;
399         }
400       /* grab ICMP ECHO content */
401       memcpy (&icmp_echo_pkt,
402               &buf[off],
403               sizeof (struct icmp_echo_header));
404       port = (uint16_t)  ntohl (icmp_echo_pkt.reserved);
405       break;
406     case IPPROTO_UDP:
407       if (have != (sizeof (struct ip_header) * 2 + 
408                    sizeof (struct icmp_ttl_exceeded_header) + 
409                    sizeof (struct udp_header)) )
410         {
411           /* malformed */
412           return;
413         }
414       /* grab UDP content */
415       memcpy (&udp_pkt,
416               &buf[off],
417               sizeof (struct udp_header));
418       port = ntohs (udp_pkt.crc);
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:%d\n",
436              inet_ntop (AF_INET,
437                         &source_ip,
438                         buf,
439                         sizeof (buf)), 
440              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  * @return -1 on error
525  */
526 static int
527 make_udp_socket (const struct in_addr *my_ip)
528 {
529   int ret;
530   struct sockaddr_in addr;
531
532   ret = socket (AF_INET, SOCK_DGRAM, 0);
533   if (-1 == ret)
534     {
535       fprintf (stderr,
536                "Error opening UDP socket: %s\n",
537                strerror (errno));
538       return -1;
539     }
540   memset (&addr, 
541           0, 
542           sizeof (addr));
543   addr.sin_family = AF_INET;
544 #if HAVE_SOCKADDR_IN_SIN_LEN
545   addr.sin_len = sizeof (struct sockaddr_in);
546 #endif
547   addr.sin_addr = *my_ip;
548   addr.sin_port = htons (NAT_TRAV_PORT);
549
550   if (0 != bind (ret,
551                  &addr,
552                  sizeof(addr)))
553     {
554       fprintf (stderr,
555                "Error binding UDP socket to port %u: %s\n",
556                NAT_TRAV_PORT,
557                strerror (errno));
558       /* likely problematic, but not certain, try to continue */
559     }
560   return ret;
561 }
562
563
564 int
565 main (int argc, 
566       char *const *argv)
567 {
568   struct in_addr external;
569   fd_set rs;
570   struct timeval tv;
571   uid_t uid;
572   unsigned int alt;
573
574   if (2 != argc)
575     {
576       fprintf (stderr,
577                "This program must be started with our (internal NAT) IP as the only argument.\n");
578       return 1;
579     }
580   if (1 != inet_pton (AF_INET, argv[1], &external))
581     {
582       fprintf (stderr,
583                "Error parsing IPv4 address: %s\n",
584                strerror (errno));
585       return 1;
586     }
587   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) 
588     {
589       fprintf (stderr,
590                "Internal error converting dummy IP to binary.\n");
591       return 2;
592     }
593   if (-1 == (icmpsock = make_icmp_socket()))
594     {
595       return 3; 
596     }
597   if (-1 == (rawsock = make_raw_socket()))
598     {
599       close (icmpsock);
600       return 3; 
601     }
602   uid = getuid ();
603   if (0 != setresuid (uid, uid, uid))
604     {
605       fprintf (stderr,
606                "Failed to setresuid: %s\n",
607                strerror (errno));    
608       /* not critical, continue anyway */
609     }
610   if (-1 == (udpsock = make_udp_socket(&external)))
611     {
612       close (icmpsock);
613       close (rawsock);
614       return 3; 
615     }
616   alt = 0;
617   while (1)
618     {
619       FD_ZERO (&rs);
620       FD_SET (icmpsock, &rs);
621       tv.tv_sec = 0;
622       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
623       if (-1 == select (icmpsock + 1, &rs, NULL, NULL, &tv))
624         {
625           if (errno == EINTR)
626             continue;
627           fprintf (stderr,
628                    "select failed: %s\n",
629                    strerror (errno));
630           break;
631         }
632       if (FD_ISSET (icmpsock, &rs))
633         process_icmp_response ();
634       if (0 == (++alt % 2))
635         send_icmp_echo (&external);
636       else
637         send_udp ();
638     }  
639   /* select failed (internal error or OS out of resources) */
640   close (icmpsock);
641   close (rawsock);
642   close (udpsock);
643   return 4;
644 }
645
646
647 /* end of gnunet-nat-server.c */