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