adding UDP server side
[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 (SUID will do)
24  *        This code will work under GNU/Linux only (or maybe BSDs, but never W32)
25  * @author Christian Grothoff
26  *
27  * This program will send ONE ICMP message every 500 ms RAW sockets
28  * to a DUMMY IP address and also listens for ICMP replies.  Since
29  * it uses RAW sockets, it must be installed SUID or run as 'root'.
30  * In order to keep the security risk of the resulting SUID binary
31  * minimal, the program ONLY opens the two RAW sockets with root
32  * privileges, then drops them and only then starts to process
33  * command line arguments.  The code also does not link against
34  * any shared libraries (except libc) and is strictly minimal
35  * (except for checking for errors).  The following list of people
36  * have reviewed this code and considered it safe since the last
37  * modification (if you reviewed it, please have your name added
38  * to the list):
39  *
40  * - Christian Grothoff
41  * - Nathan Evans
42  */
43 #if HAVE_CONFIG_H
44 /* Just needed for HAVE_SOCKADDR_IN_SIN_LEN test macro! */
45 #include "gnunet_config.h"
46 #else
47 #define _GNU_SOURCE
48 #endif
49 #include <sys/types.h> 
50 #include <sys/socket.h>
51 #include <arpa/inet.h>
52 #include <sys/select.h>
53 #include <sys/time.h>
54 #include <sys/types.h>
55 #include <unistd.h>
56 #include <stdio.h>
57 #include <string.h>
58 #include <errno.h>
59 #include <stdlib.h>
60 #include <stdint.h>
61 #include <time.h>
62 #include <netinet/ip.h>
63 #include <netinet/ip_icmp.h>
64 #include <netinet/in.h> 
65
66 /**
67  * Should we print some debug output?
68  */
69 #define VERBOSE 0
70
71 /**
72  * Must match IP given in the client.
73  */
74 #define DUMMY_IP "192.0.2.86"
75
76 /**
77  * Port for UDP
78  */ 
79 #define NAT_TRAV_PORT 22225
80
81 /**
82  * How often do we send our ICMP messages to receive replies?
83  */
84 #define ICMP_SEND_FREQUENCY_MS 500
85
86 /**
87  * IPv4 header.
88  */
89 struct ip_packet 
90 {
91
92   /**
93    * Version (4 bits) + Internet header length (4 bits) 
94    */
95   uint8_t vers_ihl;
96
97   /**
98    * Type of service
99    */
100   uint8_t tos;
101
102   /**
103    * Total length
104    */
105   uint16_t pkt_len;
106
107   /**
108    * Identification
109    */
110   uint16_t id;
111
112   /**
113    * Flags (3 bits) + Fragment offset (13 bits)
114    */
115   uint16_t flags_frag_offset;
116
117   /**
118    * Time to live
119    */
120   uint8_t ttl;
121
122   /**
123    * Protocol       
124    */
125   uint8_t proto;
126   
127   /**
128    * Header checksum
129    */
130   uint16_t checksum;
131
132   /**
133    * Source address
134    */
135   uint32_t src_ip;
136
137   /**
138    * Destination address 
139    */
140   uint32_t dst_ip;
141 };
142
143 /**
144  * Format of ICMP packet.
145  */
146 struct icmp_packet 
147 {
148   uint8_t type;
149
150   uint8_t code;
151
152   uint16_t checksum;
153
154   uint32_t reserved;
155 };
156
157 /**
158  * Beginning of UDP packet.
159  */
160 struct udp_packet
161 {
162   uint16_t src_port;
163
164   uint16_t dst_port;
165
166   uint32_t length;
167 };
168
169 /**
170  * Socket we use to receive "fake" ICMP replies.
171  */
172 static int icmpsock;
173
174 /**
175  * Socket we use to send our ICMP requests.
176  */
177 static int rawsock;
178
179 /**
180  * Socket we use to send our UDP requests.
181  */
182 static int udpsock;
183
184 /**
185  * Target "dummy" address.
186  */
187 static struct in_addr dummy;
188
189
190 /**
191  * CRC-16 for IP/ICMP headers.
192  *
193  * @param data what to calculate the CRC over
194  * @param bytes number of bytes in data (must be multiple of 2)
195  * @return the CRC 16.
196  */
197 static uint16_t 
198 calc_checksum(const uint16_t *data, 
199               unsigned int bytes)
200 {
201   uint32_t sum;
202   unsigned int i;
203
204   sum = 0;
205   for (i=0;i<bytes/2;i++) 
206     sum += data[i];        
207   sum = (sum & 0xffff) + (sum >> 16);
208   sum = htons(0xffff - sum);
209   return sum;
210 }
211
212
213 /**
214  * Send an ICMP message to the dummy IP.
215  *
216  * @param my_ip source address (our ip address)
217  */
218 static void
219 send_icmp_echo (const struct in_addr *my_ip)
220 {
221   struct icmp_packet icmp_echo;
222   struct sockaddr_in dst;
223   size_t off;
224   int err;
225   struct ip_packet ip_pkt;
226   struct icmp_packet icmp_pkt;
227   char packet[sizeof (ip_pkt) + sizeof (icmp_pkt)];
228
229   off = 0;
230   memset(&ip_pkt, 0, sizeof(ip_pkt));
231   ip_pkt.vers_ihl = 0x45;
232   ip_pkt.tos = 0;
233   ip_pkt.pkt_len = sizeof (packet);
234   ip_pkt.id = 1;
235   ip_pkt.flags_frag_offset = 0;
236   ip_pkt.ttl = IPDEFTTL;
237   ip_pkt.proto = IPPROTO_ICMP;
238   ip_pkt.checksum = 0; 
239   ip_pkt.src_ip = my_ip->s_addr;
240   ip_pkt.dst_ip = dummy.s_addr;
241   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
242   memcpy (packet, &ip_pkt, sizeof (ip_pkt));
243   off += sizeof (ip_pkt);
244
245   icmp_echo.type = ICMP_ECHO;
246   icmp_echo.code = 0;
247   icmp_echo.reserved = 0;
248   icmp_echo.checksum = 0;
249   icmp_echo.checksum = htons(calc_checksum((uint16_t*)&icmp_echo, 
250                                            sizeof (struct icmp_packet)));
251   memcpy (&packet[off], &icmp_echo, sizeof (icmp_echo));
252   off += sizeof (icmp_echo);
253  
254   memset (&dst, 0, sizeof (dst));
255   dst.sin_family = AF_INET;
256 #if HAVE_SOCKADDR_IN_SIN_LEN
257   dst.sin_len = sizeof (struct sockaddr_in);
258 #endif
259   dst.sin_addr = dummy;
260   err = sendto(rawsock, 
261                packet, off, 0, 
262                (struct sockaddr*)&dst, 
263                sizeof(dst));
264   if (err < 0) 
265     {
266 #if VERBOSE
267       fprintf(stderr,
268               "sendto failed: %s\n", strerror(errno));
269 #endif
270     }
271   else if (err != sizeof (packet)) 
272     {
273       fprintf(stderr,
274               "Error: partial send of ICMP message\n");
275     }
276 }
277
278
279 /**
280  * Send a UDP message to the dummy IP.
281  *
282  * @param my_ip source address (our ip address)
283  */
284 static void
285 send_udp (const struct in_addr *my_ip)
286 {
287   struct sockaddr_in dst;
288   ssize_t err;
289  
290   memset (&dst, 0, sizeof (dst));
291   dst.sin_family = AF_INET;
292 #if HAVE_SOCKADDR_IN_SIN_LEN
293   dst.sin_len = sizeof (struct sockaddr_in);
294 #endif
295   dst.sin_addr = dummy;
296   dst.sin_port = htons (NAT_TRAV_PORT);
297   err = sendto(udpsock, 
298                NULL, 0, 0, 
299                (struct sockaddr*)&dst, 
300                sizeof(dst));
301   if (err < 0) 
302     {
303 #if VERBOSE
304       fprintf(stderr,
305               "sendto failed: %s\n", strerror(errno));
306 #endif
307     }
308   else if (err != 0) 
309     {
310       fprintf(stderr,
311               "Error: partial send of ICMP message\n");
312     }
313 }
314
315
316
317 /**
318  * We've received an ICMP response.  Process it.
319  */
320 static void
321 process_icmp_response ()
322 {
323   char buf[65536];
324   ssize_t have;
325   struct in_addr sip;
326   struct ip_packet ip_pkt;
327   struct icmp_packet icmp_pkt;
328   struct udp_packet udp_pkt;
329   size_t off;
330   int have_port;
331   uint32_t port;
332   
333   have = read (icmpsock, buf, sizeof (buf));
334   if (have == -1)
335     {
336       fprintf (stderr,
337                "Error reading raw socket: %s\n",
338                strerror (errno));
339       return; 
340     }
341   have_port = 0;
342 #if VERBOSE
343   fprintf (stderr,
344            "Received message of %u bytes\n",
345            (unsigned int) have);
346 #endif
347   if (have == sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2 + sizeof(uint32_t))
348     {
349       have_port = 1;
350     }
351   else if (have != sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2)
352     {
353 #if VERBOSE
354       fprintf (stderr,
355                "Received ICMP message of unexpected size: %u bytes\n",
356                (unsigned int) have);
357 #endif
358       return;
359     }
360   off = 0;
361   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
362   off += sizeof (ip_pkt);
363   memcpy (&icmp_pkt, &buf[off], sizeof (icmp_pkt));
364   off += sizeof (icmp_pkt);
365   if ( ((ip_pkt.proto != IPPROTO_ICMP) && (ip_pkt.proto != IPPROTO_UDP)) ||
366        (icmp_pkt.type != ICMP_TIME_EXCEEDED) || 
367        (icmp_pkt.code != 0) )
368     {
369       /* maybe we got an actual reply back... */
370       return;    
371     }
372   memcpy(&sip, 
373          &ip_pkt.src_ip, 
374          sizeof (sip));
375   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
376   off += sizeof (ip_pkt);
377
378   if (have_port)
379     {
380       memcpy(&port, 
381              &buf[sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2],
382              sizeof(uint32_t));
383       port = ntohs(port);
384       fprintf (stdout,
385                "%s:%d\n",
386                inet_ntop (AF_INET,
387                           &sip,
388                           buf,
389                           sizeof (buf)), 
390                port);
391     }
392   else if (ip_pkt.proto == IPPROTO_UDP)
393     {
394       memcpy(&udp_pkt, 
395              &buf[off], 
396              sizeof(udp_pkt));
397       fprintf (stdout,
398                "%s:%d\n",
399                inet_ntop (AF_INET,
400                           &sip,
401                           buf,
402                           sizeof (buf)), 
403                ntohs((uint16_t) udp_pkt.length));
404     }
405   else
406     {
407       fprintf (stdout,
408                "%s\n",
409                inet_ntop (AF_INET,
410                           &sip,
411                           buf,
412                           sizeof (buf)));
413     }
414   fflush (stdout);
415 }
416
417
418 /**
419  * Create an ICMP raw socket for reading.
420  *
421  * @return -1 on error
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 /**
450  * Create an ICMP raw socket for writing.
451  *
452  * @return -1 on error
453  */
454 static int
455 make_raw_socket ()
456 {
457   const int one = 1;
458   int ret;
459
460   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
461   if (-1 == ret)
462     {
463       fprintf (stderr,
464                "Error opening RAW socket: %s\n",
465                strerror (errno));
466       return -1;
467     }  
468   if (setsockopt(ret, 
469                  SOL_SOCKET, 
470                  SO_BROADCAST,
471                  (char *)&one, 
472                  sizeof(one)) == -1)
473     {
474       fprintf(stderr,
475               "setsockopt failed: %s\n",
476               strerror (errno));
477       close (ret);
478       return -1;
479     }
480   if (setsockopt(ret, 
481                  IPPROTO_IP, 
482                  IP_HDRINCL,
483                  (char *)&one, sizeof(one)) == -1)
484     {
485       fprintf(stderr,
486               "setsockopt failed: %s\n",
487               strerror (errno));
488       close (ret);
489       return -1;
490     }
491   return ret;
492 }
493
494
495 /**
496  * Create a UDP socket for writinging.
497  *
498  * @return -1 on error
499  */
500 static int
501 make_udp_socket ()
502 {
503   int ret;
504   struct sockaddr_in addr;
505
506   ret = socket (AF_INET, SOCK_DGRAM, 0);
507   if (-1 == ret)
508     {
509       fprintf (stderr,
510                "Error opening UDP socket: %s\n",
511                strerror (errno));
512       return -1;
513     }
514   memset (&addr, 0, sizeof (addr));
515   addr.sin_family = AF_INET;
516 #if HAVE_SOCKADDR_IN_SIN_LEN
517   addr.sin_len = sizeof (struct sockaddr_in);
518 #endif
519   /* addr.sin_addr zero == ours (hopefully...) */
520   addr.sin_port = htons (NAT_TRAV_PORT);
521
522   if (0 != bind (ret,
523                  &addr,
524                  sizeof(addr)))
525     {
526       fprintf (stderr,
527                "Error binding UDP socket to port %u: %s\n",
528                NAT_TRAV_PORT,
529                strerror (errno));
530       /* likely problematic, but not certain, try to continue */
531     }
532   return ret;
533 }
534
535
536 int
537 main (int argc, 
538       char *const *argv)
539 {
540   struct in_addr external;
541   fd_set rs;
542   struct timeval tv;
543   uid_t uid;
544   unsigned int alt;
545
546   if (argc != 2)
547     {
548       fprintf (stderr,
549                "This program must be started with our (internal NAT) IP as the only argument.\n");
550       return 1;
551     }
552   if (1 != inet_pton (AF_INET, argv[1], &external))
553     {
554       fprintf (stderr,
555                "Error parsing IPv4 address: %s\n",
556                strerror (errno));
557       return 1;
558     }
559   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) 
560     {
561       fprintf (stderr,
562                "Internal error converting dummy IP to binary.\n");
563       return 2;
564     }
565   if (-1 == (icmpsock = make_icmp_socket()))
566     {
567       return 3; 
568     }
569   if (-1 == (rawsock = make_raw_socket()))
570     {
571       close (icmpsock);
572       return 3; 
573     }
574   uid = getuid ();
575   if (0 != setresuid (uid, uid, uid))
576     {
577       fprintf (stderr,
578                "Failed to setresuid: %s\n",
579                strerror (errno));    
580       /* not critical, continue anyway */
581     }
582   if (-1 == (udpsock = make_udp_socket()))
583     {
584       close (icmpsock);
585       close (rawsock);
586       return 3; 
587     }
588   alt = 0;
589   while (1)
590     {
591       FD_ZERO (&rs);
592       FD_SET (icmpsock, &rs);
593       tv.tv_sec = 0;
594       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
595       if (-1 == select (icmpsock + 1, &rs, NULL, NULL, &tv))
596         {
597           if (errno == EINTR)
598             continue;
599           fprintf (stderr,
600                    "select failed: %s\n",
601                    strerror (errno));
602           break;
603         }
604       if (FD_ISSET (icmpsock, &rs))
605         process_icmp_response ();
606       if (0 == (++alt % 2))
607         send_icmp_echo (&external);
608       else
609         send_udp (&external);
610     }  
611   /* select failed (internal error or OS out of resources) */
612   close (icmpsock);
613   close (rawsock);
614   close (udpsock);
615   return 4;
616 }
617
618
619 /* end of gnunet-nat-server.c */