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