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