cleanup
[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) htonl (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       break;
420     default:   
421       /* different type than what we want */
422       return;
423     }
424
425   if (port == 0)
426     fprintf (stdout,
427              "%s\n",
428              inet_ntop (AF_INET,
429                         &source_ip,
430                         buf,
431                         sizeof (buf)));
432   else
433     fprintf (stdout,
434              "%s:%d\n",
435              inet_ntop (AF_INET,
436                         &source_ip,
437                         buf,
438                         sizeof (buf)), 
439              port);
440   fflush (stdout);
441 }
442
443
444 /**
445  * Create an ICMP raw socket for reading.
446  *
447  * @return -1 on error
448  */
449 static int
450 make_icmp_socket ()
451 {
452   int ret;
453
454   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
455   if (-1 == ret)
456     {
457       fprintf (stderr,
458                "Error opening RAW socket: %s\n",
459                strerror (errno));
460       return -1;
461     }  
462   if (ret >= FD_SETSIZE) 
463     {
464       fprintf (stderr,
465                "Socket number too large (%d > %u)\n",
466                ret,
467                (unsigned int) FD_SETSIZE);
468       close (ret);
469       return -1;
470     }
471   return ret;
472 }
473
474
475 /**
476  * Create an ICMP raw socket for writing.
477  *
478  * @return -1 on error
479  */
480 static int
481 make_raw_socket ()
482 {
483   const int one = 1;
484   int ret;
485
486   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
487   if (-1 == ret)
488     {
489       fprintf (stderr,
490                "Error opening RAW socket: %s\n",
491                strerror (errno));
492       return -1;
493     }  
494   if (-1 == setsockopt(ret, 
495                        SOL_SOCKET, 
496                        SO_BROADCAST,
497                        (char *)&one, sizeof(one)))
498     {
499       fprintf(stderr,
500               "setsockopt failed: %s\n",
501               strerror (errno));
502       close (ret);
503       return -1;
504     }
505   if (-1 == setsockopt(ret, 
506                        IPPROTO_IP, 
507                        IP_HDRINCL,
508                        (char *)&one, sizeof(one)))
509     {
510       fprintf(stderr,
511               "setsockopt failed: %s\n",
512               strerror (errno));
513       close (ret);
514       return -1;
515     }
516   return ret;
517 }
518
519
520 /**
521  * Create a UDP socket for writinging.
522  *
523  * @return -1 on error
524  */
525 static int
526 make_udp_socket (const struct in_addr *my_ip)
527 {
528   int ret;
529   struct sockaddr_in addr;
530
531   ret = socket (AF_INET, SOCK_DGRAM, 0);
532   if (-1 == ret)
533     {
534       fprintf (stderr,
535                "Error opening UDP socket: %s\n",
536                strerror (errno));
537       return -1;
538     }
539   memset (&addr, 
540           0, 
541           sizeof (addr));
542   addr.sin_family = AF_INET;
543 #if HAVE_SOCKADDR_IN_SIN_LEN
544   addr.sin_len = sizeof (struct sockaddr_in);
545 #endif
546   addr.sin_addr = *my_ip;
547   addr.sin_port = htons (NAT_TRAV_PORT);
548
549   if (0 != bind (ret,
550                  &addr,
551                  sizeof(addr)))
552     {
553       fprintf (stderr,
554                "Error binding UDP socket to port %u: %s\n",
555                NAT_TRAV_PORT,
556                strerror (errno));
557       /* likely problematic, but not certain, try to continue */
558     }
559   return ret;
560 }
561
562
563 int
564 main (int argc, 
565       char *const *argv)
566 {
567   struct in_addr external;
568   fd_set rs;
569   struct timeval tv;
570   uid_t uid;
571   unsigned int alt;
572
573   if (2 != argc)
574     {
575       fprintf (stderr,
576                "This program must be started with our (internal NAT) IP as the only argument.\n");
577       return 1;
578     }
579   if (1 != inet_pton (AF_INET, argv[1], &external))
580     {
581       fprintf (stderr,
582                "Error parsing IPv4 address: %s\n",
583                strerror (errno));
584       return 1;
585     }
586   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) 
587     {
588       fprintf (stderr,
589                "Internal error converting dummy IP to binary.\n");
590       return 2;
591     }
592   if (-1 == (icmpsock = make_icmp_socket()))
593     {
594       return 3; 
595     }
596   if (-1 == (rawsock = make_raw_socket()))
597     {
598       close (icmpsock);
599       return 3; 
600     }
601   uid = getuid ();
602   if (0 != setresuid (uid, uid, uid))
603     {
604       fprintf (stderr,
605                "Failed to setresuid: %s\n",
606                strerror (errno));    
607       /* not critical, continue anyway */
608     }
609   if (-1 == (udpsock = make_udp_socket(&external)))
610     {
611       close (icmpsock);
612       close (rawsock);
613       return 3; 
614     }
615   alt = 0;
616   while (1)
617     {
618       FD_ZERO (&rs);
619       FD_SET (icmpsock, &rs);
620       tv.tv_sec = 0;
621       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
622       if (-1 == select (icmpsock + 1, &rs, NULL, NULL, &tv))
623         {
624           if (errno == EINTR)
625             continue;
626           fprintf (stderr,
627                    "select failed: %s\n",
628                    strerror (errno));
629           break;
630         }
631       if (FD_ISSET (icmpsock, &rs))
632         process_icmp_response ();
633       if (0 == (++alt % 2))
634         send_icmp_echo (&external);
635       else
636         send_udp ();
637     }  
638   /* select failed (internal error or OS out of resources) */
639   close (icmpsock);
640   close (rawsock);
641   close (udpsock);
642   return 4;
643 }
644
645
646 /* end of gnunet-nat-server.c */