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