fixed
[oweals/gnunet.git] / src / transport / gnunet-nat-client.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-client.c
23  * @brief Tool to help bypass NATs using ICMP method; must run as root (for now, later SUID will do)
24  *        This code will work under GNU/Linux only (or maybe BSDs, but never W32)
25  * @author Christian Grothoff
26  */
27
28 #include <sys/types.h> 
29 #include <sys/socket.h>
30 #include <arpa/inet.h>
31 #include <sys/select.h>
32 #include <sys/time.h>
33 #include <sys/types.h>
34 #include <unistd.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <errno.h>
38 #include <stdlib.h>
39 #include <stdint.h>
40 #include <netinet/ip.h>
41 #include <netinet/ip_icmp.h>
42 #include <netinet/in.h> 
43
44 #define DEBUG 0
45
46 /**
47  * Number of UDP ports to keep open (typically >= 256)
48  */
49 #define NUM_UDP_PORTS 256
50
51 /**
52  * Number of ICMP replies to send per message received (typically >= 1024)
53  */
54 #define NUM_ICMP_REPLIES 1024
55
56 /**
57  * How often do we send our UDP messages to keep ports open? (typically < 100ms)
58  */
59 #define UDP_SEND_FREQUENCY_MS 50
60
61 /**
62  * Port we use for the dummy target.
63  */
64 #define NAT_TRAV_PORT 2222
65
66 /**
67  * How often do we retry to open and bind a UDP socket before giving up?
68  */
69 #define MAX_TRIES 10
70
71 struct ip_packet 
72 {
73   uint8_t vers_ihl;
74   uint8_t tos;
75   uint16_t pkt_len;
76   uint16_t id;
77   uint16_t flags_frag_offset;
78   uint8_t ttl;
79   uint8_t proto;
80   uint16_t checksum;
81   uint32_t src_ip;
82   uint32_t dst_ip;
83 };
84
85 struct udp_packet
86 {
87   uint16_t source_port;
88   uint16_t dst_port;
89   uint16_t mlen_aka_reply_port_magic;
90   uint16_t checksum_aka_my_magic;
91 };
92
93 struct icmp_packet 
94 {
95   uint8_t type;
96   uint8_t code;
97   uint16_t checksum;
98   uint32_t reserved;
99   struct ip_packet ip;
100   struct udp_packet udp;
101 };
102
103
104 static int udpsocks[NUM_UDP_PORTS];
105
106 static uint16_t udpports[NUM_UDP_PORTS];
107  
108 static int icmpsock;
109
110 static int rawsock;
111
112 static struct in_addr dummy;
113  
114 static struct in_addr target;
115
116
117 /**
118  * create a random port number that is not totally
119  * unlikely to be chosen by the nat box.
120  */ 
121 static uint16_t make_port ()
122 {
123   return 1024 + ( (unsigned int)rand ()) % (63 * 1024 - 2);
124 }
125
126
127 /**
128  * create a fresh udp socket bound to a random local port.
129  */
130 static int
131 make_udp_socket (uint16_t *port)
132 {
133   int ret;
134   int tries;
135   struct sockaddr_in src;
136
137   for (tries=0;tries<MAX_TRIES;tries++)
138     {
139       ret = socket (AF_INET, SOCK_DGRAM, 0);
140       if (-1 == ret)
141         {
142           fprintf (stderr,
143                    "Error opening udp socket: %s\n",
144                    strerror (errno));
145           return -1;
146         }
147       if (ret >= FD_SETSIZE)       
148         {
149           fprintf (stderr,
150                    "Socket number too large (%d > %u)\n",
151                    ret,
152                    (unsigned int) FD_SETSIZE);
153           close (ret);
154           return -1;
155         }
156       memset (&src, 0, sizeof (src));
157       src.sin_family = AF_INET;
158       src.sin_port = htons (make_port ());
159       if (0 != bind (ret, (struct sockaddr*) &src, sizeof (src)))
160         {
161           close (ret);
162           continue;
163         }
164       *port = ntohs (src.sin_port);
165       return ret;
166     }
167   fprintf (stderr,
168            "Error binding udp socket: %s\n",
169            strerror (errno));
170   return -1;
171 }
172
173
174 static uint16_t 
175 calc_checksum(const uint16_t *data, 
176               unsigned int bytes)
177 {
178   uint32_t sum;
179   unsigned int i;
180
181   sum = 0;
182   for (i=0;i<bytes/2;i++) 
183     sum += data[i];        
184   sum = (sum & 0xffff) + (sum >> 16);
185   sum = htons(0xffff - sum);
186   return sum;
187 }
188
189
190 /**
191  * send an icmp message to the target.
192  *
193  * @param my_ip source address (our ip address)
194  * @param other target address
195  * @param target_port_number fake port number to put into icmp response 
196  *                           as well as the icmpextradata as 'my_magic'
197  * @param source_port_number magic_number that enables the other peer to
198  *                           identify our port number ('reply in response to') to
199  *                           put in the data portion; 0 if we are initiating;
200  *                           goes into 'reply_port_magic' of the icmpextradata
201  */
202 static void
203 send_icmp (const struct in_addr *my_ip,
204            const struct in_addr *other,
205            uint16_t target_port_number,
206            uint16_t source_port_number)
207 {
208   struct ip_packet ip_pkt;
209   struct icmp_packet icmp_pkt;
210   struct sockaddr_in dst;
211   char packet[sizeof (ip_pkt) + sizeof (icmp_pkt)];
212   size_t off;
213   int err;
214
215   /* ip header: send to (known) ip address */
216   off = 0;
217   memset(&ip_pkt, 0, sizeof(ip_pkt));
218   ip_pkt.vers_ihl = 0x45;//|(pkt_len>>2);//5;//(ipversion << 4) | (iphdr_size >> 2);
219   ip_pkt.tos = 0;
220   ip_pkt.pkt_len = sizeof (packet); /* huh? */
221   ip_pkt.id = 1; /* kernel will change anyway!? */
222   ip_pkt.flags_frag_offset = 0;
223   ip_pkt.ttl = IPDEFTTL;
224   ip_pkt.proto = IPPROTO_ICMP;
225   ip_pkt.checksum = 0;
226   ip_pkt.src_ip = my_ip->s_addr;
227   ip_pkt.dst_ip = other->s_addr;
228   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
229   memcpy (packet, &ip_pkt, sizeof (ip_pkt));
230   off += sizeof (ip_pkt);
231
232   /* icmp reply: time exceeded */
233   memset(&icmp_pkt, 0, sizeof(icmp_pkt));
234   icmp_pkt.type = ICMP_TIME_EXCEEDED;
235   icmp_pkt.code = ICMP_HOST_UNREACH;
236   icmp_pkt.reserved = 0;
237   icmp_pkt.checksum = 0;
238
239   /* ip header of the presumably 'lost' udp packet */
240   icmp_pkt.ip.vers_ihl = 0x45;
241   icmp_pkt.ip.tos = 0;
242   /* no idea why i need to shift the bits here, but not on ip_pkt->pkt_len... */
243   icmp_pkt.ip.pkt_len = (sizeof (ip_pkt) + sizeof (icmp_pkt)) << 8;
244   icmp_pkt.ip.id = 1; /* kernel sets proper value htons(ip_id_counter); */
245   icmp_pkt.ip.flags_frag_offset = 0;
246   icmp_pkt.ip.ttl = 1; /* real TTL would be 1 on a time exceeded packet */
247   icmp_pkt.ip.proto = IPPROTO_UDP;
248   icmp_pkt.ip.src_ip = other->s_addr;
249   icmp_pkt.ip.dst_ip = dummy.s_addr;
250   icmp_pkt.ip.checksum = 0;
251   icmp_pkt.ip.checksum = htons(calc_checksum((uint16_t*)&icmp_pkt.ip, sizeof (icmp_pkt.ip)));
252   icmp_pkt.udp.source_port = htons (target_port_number);
253   icmp_pkt.udp.dst_port = htons (NAT_TRAV_PORT);
254   icmp_pkt.udp.mlen_aka_reply_port_magic = htons (source_port_number);
255   icmp_pkt.udp.checksum_aka_my_magic = htons (target_port_number);
256   icmp_pkt.checksum = htons(calc_checksum((uint16_t*)&icmp_pkt, sizeof (icmp_pkt)));
257   memcpy (&packet[off], &icmp_pkt, sizeof (icmp_pkt));
258   off += sizeof (icmp_pkt);
259   
260   memset (&dst, 0, sizeof (dst));
261   dst.sin_family = AF_INET;
262   dst.sin_addr = *other;
263   err = sendto(rawsock, 
264                packet, 
265                off, 0, 
266                (struct sockaddr*)&dst, 
267                sizeof(dst)); /* or sizeof 'struct sockaddr'? */
268   if (err < 0) {
269     fprintf(stderr,
270             "sendto failed: %s\n", strerror(errno));
271   } else if (err != off) 
272     fprintf(stderr,
273             "Error: partial send of ICMP message\n");
274 }
275
276
277 /**
278  * We discovered the IP address of the other peer.
279  * Try to connect back to it.
280  */
281 static void
282 try_connect (const struct in_addr *my_ip,
283              const struct in_addr *other,
284              uint16_t port_magic)
285 {
286   unsigned int i;
287   char sbuf [INET_ADDRSTRLEN];
288
289   fprintf (stderr,
290            "Sending %u ICMPs to `%s' with reply magic %u\n",
291            NUM_ICMP_REPLIES,
292            inet_ntop (AF_INET,
293                       other,
294                       sbuf,
295                       sizeof (sbuf)),
296            port_magic);
297   for (i=0;i<NUM_ICMP_REPLIES;i++)
298     send_icmp (my_ip, other, make_port(), port_magic);
299 }
300
301
302 static void
303 process_icmp_response (const struct in_addr *my_ip,
304                        int s)
305 {
306   char buf[65536];
307   ssize_t have;
308   struct in_addr sip;
309   uint16_t my_magic;
310   uint16_t reply_magic;
311   uint16_t local_port;
312   struct ip_packet ip_pkt;
313   struct icmp_packet icmp_pkt;
314   size_t off;
315   
316   have = read (s, buf, sizeof (buf));
317   if (have == -1)
318     {
319       fprintf (stderr,
320                "Error reading raw socket: %s\n",
321                strerror (errno));
322       /* What now? */
323       return; 
324     }
325   if (have != sizeof (struct ip_packet) + sizeof (struct icmp_packet))
326     {
327       fprintf (stderr,
328                "Received ICMP message of unexpected size: %u bytes\n",
329                (unsigned int) have);
330       return;
331     }
332   off = 0;
333   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
334   off += sizeof (ip_pkt);
335   memcpy (&icmp_pkt, &buf[off], sizeof (icmp_pkt));
336   off += sizeof (icmp_pkt);
337
338   if ( (ip_pkt.proto == IPPROTO_ICMP) &&
339        (icmp_pkt.type == ICMP_DEST_UNREACH) && 
340        (icmp_pkt.code == ICMP_HOST_UNREACH) )
341     {
342       /* this is what is normal due to our UDP traffic */
343       return;
344     }
345   if ( (ip_pkt.proto == IPPROTO_ICMP) &&
346        (icmp_pkt.type == ICMP_TIME_EXCEEDED) &&
347        (icmp_pkt.code == ICMP_HOST_UNREACH) )
348     {
349       /* this is what we might see on loopback: this is the format
350          we as the client send out (the host uses 'ICMP_NET_UNREACH');
351          Ignore! */
352       return;
353     }
354   if ( (ip_pkt.proto != IPPROTO_ICMP) ||
355        (icmp_pkt.type != ICMP_TIME_EXCEEDED) || 
356        (icmp_pkt.code != ICMP_NET_UNREACH) )
357     {
358       /* Note the expected client response and not the normal network response */
359 #if DEBUG
360       fprintf (stderr,
361                "Received unexpected ICMP message contents (%u, %u, %u), ignoring\n",
362                ip_pkt.proto,
363                icmp_pkt.type,
364                icmp_pkt.code);
365 #endif
366       return;
367     }
368   memcpy(&sip, &ip_pkt.src_ip, sizeof (sip));
369   reply_magic = ntohs (icmp_pkt.udp.checksum_aka_my_magic);
370   my_magic = ntohs (icmp_pkt.udp.mlen_aka_reply_port_magic);
371   local_port = ntohs (icmp_pkt.udp.source_port);
372   if  (my_magic == 0)
373     {
374 #if DEBUG
375       /* we get these a lot during loopback testing... */
376       fprintf (stderr,
377                "Received ICMP without hint as to which port worked, dropping\n");
378 #endif
379       return;
380     }
381 #if DEBUG
382   fprintf (stderr,
383            "Received ICMP from `%s' with outgoing port %u, listen port %u and incoming for other peer %u\n",
384            inet_ntop (AF_INET,
385                       &sip,
386                       buf,
387                       sizeof (buf)),
388            my_magic,
389            local_port,
390            reply_magic);
391 #endif
392   if (my_magic == 0)
393     {
394       try_connect (my_ip, &sip, reply_magic);
395     }
396   else
397     {
398       send_icmp (my_ip, &target, my_magic, reply_magic);
399       printf ("%s:%u listen on %u\n",
400               inet_ntop (AF_INET,
401                          &sip,
402                          buf,
403                          sizeof(buf)),
404               my_magic,
405               local_port);
406       /* technically, we're done here! */      
407       exit (0);
408     }
409 }
410
411
412 static int
413 make_icmp_socket ()
414 {
415   int ret;
416
417   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
418   if (-1 == ret)
419     {
420       fprintf (stderr,
421                "Error opening RAW socket: %s\n",
422                strerror (errno));
423       return -1;
424     }  
425   if (ret >= FD_SETSIZE) 
426     {
427       fprintf (stderr,
428                "Socket number too large (%d > %u)\n",
429                ret,
430                (unsigned int) FD_SETSIZE);
431       close (ret);
432       return -1;
433     }
434   return ret;
435 }
436
437
438 static int
439 make_raw_socket ()
440 {
441   const int one = 1;
442   int ret;
443
444   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
445   if (-1 == ret)
446     {
447       fprintf (stderr,
448                "Error opening RAW socket: %s\n",
449                strerror (errno));
450       return -1;
451     }  
452   if (ret >= FD_SETSIZE) 
453     {
454       fprintf (stderr,
455                "Socket number too large (%d > %u)\n",
456                ret,
457                (unsigned int) FD_SETSIZE);
458       close (ret);
459       return -1;
460     }
461   if (setsockopt(ret, SOL_SOCKET, SO_BROADCAST,
462                  (char *)&one, sizeof(one)) == -1)
463     fprintf(stderr,
464             "setsockopt failed: %s\n",
465             strerror (errno));
466   if (setsockopt(ret, IPPROTO_IP, IP_HDRINCL,
467                  (char *)&one, sizeof(one)) == -1)
468     fprintf(stderr,
469             "setsockopt failed: %s\n",
470             strerror (errno));
471   return ret;
472 }
473
474
475 int
476 main (int argc, char *const *argv)
477 {
478   struct in_addr external;
479   unsigned int i;  
480   unsigned int pos;
481   fd_set rs;
482   struct timeval tv;
483   struct sockaddr_in dst;  
484   uint16_t p;
485   
486   if (argc != 4)
487     {
488       fprintf (stderr,
489                "This program must be started with our IP, the targets external IP and the dummy IP address as arguments.\n");
490       return 1;
491     }
492   if ( (1 != inet_pton (AF_INET, argv[1], &external)) ||
493        (1 != inet_pton (AF_INET, argv[2], &target)) ||
494        (1 != inet_pton (AF_INET, argv[3], &dummy)) )
495     {
496       fprintf (stderr,
497                "Error parsing IPv4 address: %s\n",
498                strerror (errno));
499       return 1;
500     }
501   memset (&dst, 0, sizeof (dst));
502   dst.sin_family = AF_INET;
503   dst.sin_port = htons (NAT_TRAV_PORT);
504   dst.sin_addr = dummy;
505
506   if (-1 == (icmpsock = make_icmp_socket()))
507     return 1; 
508   if (-1 == (rawsock = make_raw_socket()))
509     {
510       close (icmpsock);
511       return 1; 
512     }
513   for (i=0;i<NUM_UDP_PORTS;i++)
514     udpsocks[i] = make_udp_socket (&udpports[i]);
515   pos = 0;
516   while (1)
517     {
518       FD_ZERO (&rs);
519       FD_SET (icmpsock, &rs);
520       tv.tv_sec = 0;
521       tv.tv_usec = UDP_SEND_FREQUENCY_MS * 1000; 
522       select (icmpsock + 1, &rs, NULL, NULL, &tv);
523       /* FIXME: do I need my external IP here? */
524       if (FD_ISSET (icmpsock, &rs))
525         {
526           process_icmp_response (&external, icmpsock);
527           continue;
528         }
529 #if DEBUG
530       fprintf (stderr,
531                "Sending UDP message to %s:%u\n",
532                argv[3],
533                NAT_TRAV_PORT);      
534 #endif
535       if (-1 == sendto (udpsocks[pos],
536                         NULL, 0, 0,
537                         (struct sockaddr*) &dst, sizeof (dst)))
538         {
539           fprintf (stderr, 
540                    "sendto failed: %s\n",
541                    strerror (errno));
542           close (udpsocks[pos]);
543           udpsocks[pos] = make_udp_socket (&udpports[pos]);
544         }
545       p = make_port ();
546 #if DEBUG
547       fprintf (stderr,
548                "Sending fake ICMP message to %s:%u\n",
549                argv[1],
550                p);      
551 #endif
552       send_icmp (&external,
553                  &target,
554                  p,
555                  0);
556       pos = (pos+1) % NUM_UDP_PORTS;
557     }  
558   return 0;
559 }
560
561
562 /* end of gnunet-nat-client.c */