stuff
[oweals/gnunet.git] / src / transport / gnunet-nat-client.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-client.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.  
25  * @author Christian Grothoff
26  *
27  * This program will send ONE ICMP message using RAW sockets
28  * to the IP address specified as the second argument.  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 RAW socket 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/types.h>
53 #include <unistd.h>
54 #include <stdio.h>
55 #include <string.h>
56 #include <errno.h>
57 #include <stdlib.h>
58 #include <stdint.h>
59 #include <netinet/ip.h>
60 #include <netinet/ip_icmp.h>
61 #include <netinet/in.h> 
62
63 /**
64  * Must match IP given in the server.
65  */
66 #define DUMMY_IP "192.0.2.86"
67
68 #define NAT_TRAV_PORT 22225
69
70 /**
71  * IPv4 header.
72  */
73 struct ip_header 
74 {
75
76   /**
77    * Version (4 bits) + Internet header length (4 bits) 
78    */
79   uint8_t vers_ihl;
80
81   /**
82    * Type of service
83    */
84   uint8_t tos;
85
86   /**
87    * Total length
88    */
89   uint16_t pkt_len;
90
91   /**
92    * Identification
93    */
94   uint16_t id;
95
96   /**
97    * Flags (3 bits) + Fragment offset (13 bits)
98    */
99   uint16_t flags_frag_offset;
100
101   /**
102    * Time to live
103    */
104   uint8_t ttl;
105
106   /**
107    * Protocol       
108    */
109   uint8_t proto;
110   
111   /**
112    * Header checksum
113    */
114   uint16_t checksum;
115
116   /**
117    * Source address
118    */
119   uint32_t src_ip;
120
121   /**
122    * Destination address 
123    */
124   uint32_t dst_ip;
125 };
126
127 /**
128  * Format of ICMP packet.
129  */
130 struct icmp_ttl_exceeded_header 
131 {
132   uint8_t type;
133
134   uint8_t code;
135
136   uint16_t checksum;
137
138   uint32_t unused;
139
140   /* followed by original payload */
141 };
142
143 struct icmp_echo_header
144 {
145   uint8_t type;
146
147   uint8_t code;
148
149   uint16_t checksum;
150
151   uint32_t reserved;
152 };
153
154 /**
155  * Beginning of UDP packet.
156  */
157 struct udp_header
158 {
159   uint16_t src_port;
160
161   uint16_t dst_port;
162
163   uint16_t length;
164   
165   uint16_t crc;
166 };
167
168 /**
169  * Socket we use to send our fake ICMP replies.
170  */
171 static int rawsock;
172
173 /**
174  * Target "dummy" address of the packet we pretend to respond to.
175  */
176 static struct in_addr dummy;
177  
178 /**
179  * Our "source" port.
180  */
181 static uint16_t port;
182
183
184 /**
185  * CRC-16 for IP/ICMP headers.
186  *
187  * @param data what to calculate the CRC over
188  * @param bytes number of bytes in data (must be multiple of 2)
189  * @return the CRC 16.
190  */
191 static uint16_t 
192 calc_checksum (const uint16_t *data, 
193                unsigned int bytes)
194 {
195   uint32_t sum;
196   unsigned int i;
197
198   sum = 0;
199   for (i=0;i<bytes/2;i++) 
200     sum += data[i];        
201   sum = (sum & 0xffff) + (sum >> 16);
202   sum = htons(0xffff - sum);
203   return sum;
204 }
205
206
207 /**
208  * Send an ICMP message to the target.
209  *
210  * @param my_ip source address
211  * @param other target address
212  */
213 static void
214 send_icmp_udp (const struct in_addr *my_ip,
215                const struct in_addr *other)
216 {
217   char packet[sizeof(struct ip_header) * 2 + 
218               sizeof(struct icmp_ttl_exceeded_header) + 
219               sizeof(struct udp_header)];
220   struct ip_header ip_pkt;
221   struct icmp_ttl_exceeded_header icmp_pkt;
222   struct udp_header udp_pkt;
223   struct sockaddr_in dst;
224   size_t off;
225   int err;
226
227   /* ip header: send to (known) ip address */
228   off = 0;
229   ip_pkt.vers_ihl = 0x45;
230   ip_pkt.tos = 0;
231   ip_pkt.pkt_len = htons(sizeof (packet));
232   ip_pkt.id = htons(256);
233   ip_pkt.flags_frag_offset = 0;
234   ip_pkt.ttl = 128;
235   ip_pkt.proto = IPPROTO_ICMP;
236   ip_pkt.checksum = 0;
237   ip_pkt.src_ip = my_ip->s_addr;
238   ip_pkt.dst_ip = other->s_addr;
239   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, 
240                                         sizeof (struct ip_header)));
241   memcpy(&packet[off], 
242          &ip_pkt, 
243          sizeof(struct ip_header));
244   off += sizeof(struct ip_header);
245
246   icmp_pkt.type = ICMP_TIME_EXCEEDED;
247   icmp_pkt.code = 0;
248   icmp_pkt.checksum = 0;
249   icmp_pkt.unused = 0;
250   memcpy(&packet[off],
251          &icmp_pkt, 
252          sizeof(struct icmp_ttl_exceeded_header));
253   off += sizeof(struct icmp_ttl_exceeded_header);
254
255   /* ip header of the presumably 'lost' udp packet */
256   ip_pkt.vers_ihl = 0x45;
257   ip_pkt.tos = 0;
258   ip_pkt.pkt_len = htons(sizeof (struct ip_header) +
259                          sizeof(struct udp_header));
260   ip_pkt.id = htons(0);
261   ip_pkt.flags_frag_offset = 0;
262   ip_pkt.ttl = 128;
263   ip_pkt.proto = IPPROTO_UDP;
264   ip_pkt.checksum = 0;
265   ip_pkt.src_ip = other->s_addr;
266   ip_pkt.dst_ip = dummy.s_addr;
267   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt,
268                                         sizeof (struct ip_header)));
269   memcpy(&packet[off], 
270          &ip_pkt, 
271          sizeof(struct ip_header));
272   off += sizeof(struct ip_header);
273
274   /* build UDP header */
275   udp_pkt.src_port = htons(NAT_TRAV_PORT);
276   udp_pkt.dst_port = htons(NAT_TRAV_PORT);
277   udp_pkt.length = htons (port);
278   udp_pkt.crc = 0;
279   memcpy(&packet[off], 
280          &udp_pkt,
281          sizeof(struct udp_header));
282   off += sizeof(struct udp_header);
283
284   /* set ICMP checksum */
285   icmp_pkt.checksum = htons(calc_checksum((uint16_t*)&packet[sizeof(struct ip_header)],
286                                           sizeof (struct icmp_ttl_exceeded_header) +
287                                           sizeof (struct ip_header) +
288                                           sizeof (struct udp_header)));
289   memcpy (&packet[sizeof(struct ip_header)], 
290           &icmp_pkt, 
291           sizeof (struct icmp_ttl_exceeded_header));  
292   memset (&dst, 0, sizeof (dst));
293   dst.sin_family = AF_INET;
294 #if HAVE_SOCKADDR_IN_SIN_LEN
295   dst.sin_len = sizeof (struct sockaddr_in);
296 #endif
297   dst.sin_addr = *other;
298   err = sendto(rawsock,
299                packet,
300                off, 0,
301                (struct sockaddr*)&dst,
302                sizeof(dst));
303   if (err < 0)
304     {
305       fprintf(stderr,
306               "sendto failed: %s\n", strerror(errno));
307     }
308   else if (off != (size_t) err)
309     {
310       fprintf(stderr,
311               "Error: partial send of ICMP message\n");
312     }
313 }
314
315
316 /**
317  * Send an ICMP message to the target.
318  *
319  * @param my_ip source address
320  * @param other target address
321  */
322 static void
323 send_icmp (const struct in_addr *my_ip,
324            const struct in_addr *other)
325 {
326   struct ip_header ip_pkt;
327   struct icmp_ttl_exceeded_header icmp_pkt;
328   struct icmp_echo_header icmp_echo;
329   struct sockaddr_in dst;
330   char packet[sizeof (struct ip_header) * 2 +
331               sizeof (struct icmp_ttl_exceeded_header) +
332               sizeof (struct icmp_echo_header)];
333   size_t off;
334   int err;
335
336   /* ip header: send to (known) ip address */
337   off = 0;
338   ip_pkt.vers_ihl = 0x45;
339   ip_pkt.tos = 0;
340   ip_pkt.pkt_len = sizeof (packet);
341   ip_pkt.id = 1; 
342   ip_pkt.flags_frag_offset = 0;
343   ip_pkt.ttl = IPDEFTTL;
344   ip_pkt.proto = IPPROTO_ICMP;
345   ip_pkt.checksum = 0; 
346   ip_pkt.src_ip = my_ip->s_addr;
347   ip_pkt.dst_ip = other->s_addr;
348   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, 
349                                         sizeof (struct ip_header)));
350   memcpy (&packet[off], 
351           &ip_pkt, 
352           sizeof (struct ip_header));
353   off = sizeof (ip_pkt);
354
355   /* icmp reply: time exceeded */
356   icmp_pkt.type = ICMP_TIME_EXCEEDED;
357   icmp_pkt.code = 0; 
358   icmp_pkt.checksum = 0;
359   icmp_pkt.unused = 0;
360   memcpy (&packet[off],
361           &icmp_pkt,
362           sizeof (struct icmp_ttl_exceeded_header));
363   off += sizeof (struct icmp_ttl_exceeded_header);
364
365   /* ip header of the presumably 'lost' udp packet */
366   ip_pkt.vers_ihl = 0x45;
367   ip_pkt.tos = 0;
368   ip_pkt.pkt_len = (sizeof (struct ip_header) + sizeof (struct icmp_echo_header));
369   ip_pkt.id = 1; 
370   ip_pkt.flags_frag_offset = 0;
371   ip_pkt.ttl = 1; /* real TTL would be 1 on a time exceeded packet */
372   ip_pkt.proto = IPPROTO_ICMP;
373   ip_pkt.src_ip = other->s_addr;
374   ip_pkt.dst_ip = dummy.s_addr;
375   ip_pkt.checksum = 0;
376   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt,
377                                         sizeof (struct ip_header)));  
378   memcpy (&packet[off], 
379           &ip_pkt, 
380           sizeof (struct ip_header));
381   off += sizeof (struct ip_header);
382
383   icmp_echo.type = ICMP_ECHO;
384   icmp_echo.code = 0;
385   icmp_echo.reserved = htonl (port);
386   icmp_echo.checksum = 0;
387   icmp_echo.checksum = htons(calc_checksum((uint16_t*) &icmp_echo, 
388                                            sizeof (struct icmp_echo_header)));
389   memcpy (&packet[off], 
390           &icmp_echo,
391           sizeof(struct icmp_echo_header));
392
393   /* no go back to calculate ICMP packet checksum */
394   off = sizeof (struct ip_header);
395   icmp_pkt.checksum = htons(calc_checksum((uint16_t*) &packet[off],
396                                           sizeof (struct icmp_ttl_exceeded_header) + 
397                                           sizeof(struct ip_header) + 
398                                           sizeof(struct icmp_echo_header)));
399   memcpy (&packet[off],
400           &icmp_pkt,
401           sizeof (struct icmp_ttl_exceeded_header));
402
403   /* prepare for transmission */
404   memset (&dst, 0, sizeof (dst));
405   dst.sin_family = AF_INET;
406 #if HAVE_SOCKADDR_IN_SIN_LEN
407   dst.sin_len = sizeof (struct sockaddr_in);
408 #endif
409   dst.sin_addr = *other;
410   err = sendto(rawsock, 
411                packet, 
412                sizeof (packet), 0, 
413                (struct sockaddr*)&dst, 
414                sizeof(struct sockaddr_in));
415   if (err < 0) 
416     {
417       fprintf(stderr,
418               "sendto failed: %s\n", strerror(errno));
419     }
420   else if (sizeof (packet) != (size_t) err) 
421     {
422       fprintf(stderr,
423               "Error: partial send of ICMP message\n");
424     }
425 }
426
427
428 /**
429  * Create an ICMP raw socket for writing.
430  *
431  * @return -1 on error
432  */
433 static int
434 make_raw_socket ()
435 {
436   const int one = 1;
437   int ret;
438
439   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
440   if (-1 == ret)
441     {
442       fprintf (stderr,
443                "Error opening RAW socket: %s\n",
444                strerror (errno));
445       return -1;
446     }  
447   if (-1 == setsockopt(ret, SOL_SOCKET, SO_BROADCAST,
448                        (char *)&one, sizeof(one)))
449     {
450       fprintf(stderr,
451               "setsockopt failed: %s\n",
452               strerror (errno));
453       close (ret);
454       return -1;
455     }
456   if (-1 == setsockopt(ret, IPPROTO_IP, IP_HDRINCL,
457                        (char *)&one, sizeof(one)))
458     {
459       fprintf(stderr,
460               "setsockopt failed: %s\n",
461               strerror (errno));
462       close (ret);
463       return -1;
464     }
465   return ret;
466 }
467
468
469 int
470 main (int argc, char *const *argv)
471 {
472   struct in_addr external;
473   struct in_addr target;
474   uid_t uid;
475   unsigned int p;
476
477   if (4 != argc)
478     {
479       fprintf (stderr,
480                "This program must be started with our IP, the targets external IP, and our port 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], &target)) )
485     {
486       fprintf (stderr,
487                "Error parsing IPv4 address: %s\n",
488                strerror (errno));
489       return 1;
490     }
491   if ( (1 != sscanf (argv[3], "%u", &p) ) ||
492        (0 == p) ||
493        (0xFFFF < p) )
494     {
495       fprintf (stderr,
496                "Error parsing port value `%s'\n",
497                argv[3]);
498       return 1;
499     }
500   port = (uint16_t) p;
501   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) 
502     {
503       fprintf (stderr,
504                "Internal error converting dummy IP to binary.\n");
505       return 2;
506     }
507   if (-1 == (rawsock = make_raw_socket()))
508     return 2;     
509   uid = getuid ();
510   if (0 != setresuid (uid, uid, uid))
511     {
512       fprintf (stderr,
513                "Failed to setresuid: %s\n",
514                strerror (errno));
515       /* not critical, continue anyway */
516     }
517   send_icmp (&external,
518              &target);
519   send_icmp_udp (&external,
520                  &target);
521   close (rawsock);
522   return 0;
523 }
524
525 /* end of gnunet-nat-client.c */