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