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