more code cleanup
[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  * How often do we send our ICMP messages to receive replies?
78  */
79 #define ICMP_SEND_FREQUENCY_MS 500
80
81 /**
82  * IPv4 header.
83  */
84 struct ip_packet 
85 {
86
87   /**
88    * Version (4 bits) + Internet header length (4 bits) 
89    */
90   uint8_t vers_ihl;
91
92   /**
93    * Type of service
94    */
95   uint8_t tos;
96
97   /**
98    * Total length
99    */
100   uint16_t pkt_len;
101
102   /**
103    * Identification
104    */
105   uint16_t id;
106
107   /**
108    * Flags (3 bits) + Fragment offset (13 bits)
109    */
110   uint16_t flags_frag_offset;
111
112   /**
113    * Time to live
114    */
115   uint8_t ttl;
116
117   /**
118    * Protocol       
119    */
120   uint8_t proto;
121   
122   /**
123    * Header checksum
124    */
125   uint16_t checksum;
126
127   /**
128    * Source address
129    */
130   uint32_t src_ip;
131
132   /**
133    * Destination address 
134    */
135   uint32_t dst_ip;
136 };
137
138 /**
139  * Format of ICMP packet.
140  */
141 struct icmp_packet 
142 {
143   uint8_t type;
144
145   uint8_t code;
146
147   uint16_t checksum;
148
149   uint32_t reserved;
150 };
151
152 /**
153  * Beginning of UDP packet.
154  */
155 struct udp_packet
156 {
157   uint16_t src_port;
158
159   uint16_t dst_port;
160
161   uint32_t length;
162 };
163
164 /**
165  * Socket we use to receive "fake" ICMP replies.
166  */
167 static int icmpsock;
168
169 /**
170  * Socket we use to send our ICMP requests.
171  */
172 static int rawsock;
173
174 /**
175  * Target "dummy" address.
176  */
177 static struct in_addr dummy;
178
179
180 /**
181  * CRC-16 for IP/ICMP headers.
182  *
183  * @param data what to calculate the CRC over
184  * @param bytes number of bytes in data (must be multiple of 2)
185  * @return the CRC 16.
186  */
187 static uint16_t 
188 calc_checksum(const uint16_t *data, 
189               unsigned int bytes)
190 {
191   uint32_t sum;
192   unsigned int i;
193
194   sum = 0;
195   for (i=0;i<bytes/2;i++) 
196     sum += data[i];        
197   sum = (sum & 0xffff) + (sum >> 16);
198   sum = htons(0xffff - sum);
199   return sum;
200 }
201
202
203 /**
204  * Send an ICMP message to the dummy IP.
205  *
206  * @param my_ip source address (our ip address)
207  */
208 static void
209 send_icmp_echo (const struct in_addr *my_ip)
210 {
211   struct icmp_packet icmp_echo;
212   struct sockaddr_in dst;
213   size_t off;
214   int err;
215   struct ip_packet ip_pkt;
216   struct icmp_packet icmp_pkt;
217   char packet[sizeof (ip_pkt) + sizeof (icmp_pkt)];
218
219   off = 0;
220   memset(&ip_pkt, 0, sizeof(ip_pkt));
221   ip_pkt.vers_ihl = 0x45;
222   ip_pkt.tos = 0;
223   ip_pkt.pkt_len = sizeof (packet);
224   ip_pkt.id = 1;
225   ip_pkt.flags_frag_offset = 0;
226   ip_pkt.ttl = IPDEFTTL;
227   ip_pkt.proto = IPPROTO_ICMP;
228   ip_pkt.checksum = 0; 
229   ip_pkt.src_ip = my_ip->s_addr;
230   ip_pkt.dst_ip = dummy.s_addr;
231   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
232   memcpy (packet, &ip_pkt, sizeof (ip_pkt));
233   off += sizeof (ip_pkt);
234
235   icmp_echo.type = ICMP_ECHO;
236   icmp_echo.code = 0;
237   icmp_echo.reserved = 0;
238   icmp_echo.checksum = 0;
239   icmp_echo.checksum = htons(calc_checksum((uint16_t*)&icmp_echo, 
240                                            sizeof (struct icmp_packet)));
241   memcpy (&packet[off], &icmp_echo, sizeof (icmp_echo));
242   off += sizeof (icmp_echo);
243  
244   memset (&dst, 0, sizeof (dst));
245   dst.sin_family = AF_INET;
246 #if HAVE_SOCKADDR_IN_SIN_LEN
247   dst.sin_len = sizeof (struct sockaddr_in);
248 #endif
249   dst.sin_addr = dummy;
250   err = sendto(rawsock, 
251                packet, off, 0, 
252                (struct sockaddr*)&dst, 
253                sizeof(dst));
254   if (err < 0) 
255     {
256 #if VERBOSE
257       fprintf(stderr,
258               "sendto failed: %s\n", strerror(errno));
259 #endif
260     }
261   else if (err != off) 
262     {
263       fprintf(stderr,
264               "Error: partial send of ICMP message\n");
265     }
266 }
267
268
269 /**
270  * We've received an ICMP response.  Process it.
271  */
272 static void
273 process_icmp_response ()
274 {
275   char buf[65536];
276   ssize_t have;
277   struct in_addr sip;
278   struct ip_packet ip_pkt;
279   struct icmp_packet icmp_pkt;
280   struct udp_packet udp_pkt;
281   size_t off;
282   int have_port;
283   uint32_t port;
284   
285   have = read (icmpsock, buf, sizeof (buf));
286   if (have == -1)
287     {
288       fprintf (stderr,
289                "Error reading raw socket: %s\n",
290                strerror (errno));
291       return; 
292     }
293   have_port = 0;
294 #if VERBOSE
295   fprintf (stderr,
296            "Received message of %u bytes\n",
297            (unsigned int) have);
298 #endif
299   if (have == sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2 + sizeof(uint32_t))
300     {
301       have_port = 1;
302     }
303   else if (have != sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2)
304     {
305 #if VERBOSE
306       fprintf (stderr,
307                "Received ICMP message of unexpected size: %u bytes\n",
308                (unsigned int) have);
309 #endif
310       return;
311     }
312   off = 0;
313   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
314   off += sizeof (ip_pkt);
315   memcpy (&icmp_pkt, &buf[off], sizeof (icmp_pkt));
316   off += sizeof (icmp_pkt);
317   if ( ((ip_pkt.proto != IPPROTO_ICMP) && (ip_pkt.proto != IPPROTO_UDP)) ||
318        (icmp_pkt.type != ICMP_TIME_EXCEEDED) || 
319        (icmp_pkt.code != 0) )
320     {
321       /* maybe we got an actual reply back... */
322       return;    
323     }
324   memcpy(&sip, 
325          &ip_pkt.src_ip, 
326          sizeof (sip));
327   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
328   off += sizeof (ip_pkt);
329
330   if (have_port)
331     {
332       memcpy(&port, 
333              &buf[sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2],
334              sizeof(uint32_t));
335       port = ntohs(port);
336       fprintf (stdout,
337                "%s:%d\n",
338                inet_ntop (AF_INET,
339                           &sip,
340                           buf,
341                           sizeof (buf)), 
342                port);
343     }
344   else if (ip_pkt.proto == IPPROTO_UDP)
345     {
346       memcpy(&udp_pkt, 
347              &buf[off], 
348              sizeof(udp_pkt));
349       fprintf (stdout,
350                "%s:%d\n",
351                inet_ntop (AF_INET,
352                           &sip,
353                           buf,
354                           sizeof (buf)), 
355                ntohs((uint16_t) udp_pkt.length));
356     }
357   else
358     {
359       fprintf (stdout,
360                "%s\n",
361                inet_ntop (AF_INET,
362                           &sip,
363                           buf,
364                           sizeof (buf)));
365     }
366   fflush (stdout);
367 }
368
369
370 /**
371  * Create an ICMP raw socket for reading.
372  *
373  * @return -1 on error
374  */
375 static int
376 make_icmp_socket ()
377 {
378   int ret;
379
380   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
381   if (-1 == ret)
382     {
383       fprintf (stderr,
384                "Error opening RAW socket: %s\n",
385                strerror (errno));
386       return -1;
387     }  
388   if (ret >= FD_SETSIZE) 
389     {
390       fprintf (stderr,
391                "Socket number too large (%d > %u)\n",
392                ret,
393                (unsigned int) FD_SETSIZE);
394       close (ret);
395       return -1;
396     }
397   return ret;
398 }
399
400
401 /**
402  * Create an ICMP raw socket for writing.
403  *
404  * @return -1 on error
405  */
406 static int
407 make_raw_socket ()
408 {
409   const int one = 1;
410   int ret;
411
412   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
413   if (-1 == ret)
414     {
415       fprintf (stderr,
416                "Error opening RAW socket: %s\n",
417                strerror (errno));
418       return -1;
419     }  
420   if (setsockopt(ret, 
421                  SOL_SOCKET, 
422                  SO_BROADCAST,
423                  (char *)&one, 
424                  sizeof(one)) == -1)
425     {
426       fprintf(stderr,
427               "setsockopt failed: %s\n",
428               strerror (errno));
429       close (ret);
430       return -1;
431     }
432   if (setsockopt(ret, 
433                  IPPROTO_IP, 
434                  IP_HDRINCL,
435                  (char *)&one, sizeof(one)) == -1)
436     {
437       fprintf(stderr,
438               "setsockopt failed: %s\n",
439               strerror (errno));
440       close (ret);
441       return -1;
442     }
443   return ret;
444 }
445
446
447 int
448 main (int argc, 
449       char *const *argv)
450 {
451   struct in_addr external;
452   fd_set rs;
453   struct timeval tv;
454   uid_t uid;
455
456   if (argc != 2)
457     {
458       fprintf (stderr,
459                "This program must be started with our (internal NAT) IP as the only argument.\n");
460       return 1;
461     }
462   if (1 != inet_pton (AF_INET, argv[1], &external))
463     {
464       fprintf (stderr,
465                "Error parsing IPv4 address: %s\n",
466                strerror (errno));
467       return 1;
468     }
469   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) 
470     {
471       fprintf (stderr,
472                "Internal error converting dummy IP to binary.\n");
473       return 2;
474     }
475   if (-1 == (icmpsock = make_icmp_socket()))
476     {
477       return 3; 
478     }
479   if (-1 == (rawsock = make_raw_socket()))
480     {
481       close (icmpsock);
482       return 3; 
483     }
484   uid = getuid ();
485   if (0 != setresuid (uid, uid, uid))
486     {
487       fprintf (stderr,
488                "Failed to setresuid: %s\n",
489                strerror (errno));    
490       /* not critical, continue anyway */
491     }
492   while (1)
493     {
494       FD_ZERO (&rs);
495       FD_SET (icmpsock, &rs);
496       tv.tv_sec = 0;
497       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
498       if (-1 == select (icmpsock + 1, &rs, NULL, NULL, &tv))
499         {
500           if (errno == EINTR)
501             continue;
502           fprintf (stderr,
503                    "select failed: %s\n",
504                    strerror (errno));
505           break;
506         }
507       if (FD_ISSET (icmpsock, &rs))
508         process_icmp_response ();
509       send_icmp_echo (&external);
510     }  
511   /* select failed (internal error or OS out of resources) */
512   close (icmpsock);
513   close (rawsock);
514   return 4;
515 }
516
517
518 /* end of gnunet-nat-server.c */