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