cleaning
[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
293   memset (&dst, 0, sizeof (dst));
294   dst.sin_family = AF_INET;
295 #if HAVE_SOCKADDR_IN_SIN_LEN
296   dst.sin_len = sizeof (struct sockaddr_in);
297 #endif
298   dst.sin_addr = *other;
299   err = sendto(rawsock,
300                packet,
301                sizeof (packet), 0,
302                (struct sockaddr*)&dst,
303                sizeof(dst));
304   if (err < 0)
305     {
306       fprintf(stderr,
307               "sendto failed: %s\n", strerror(errno));
308     }
309   else if (sizeof (packet) != (size_t) err)
310     {
311       fprintf(stderr,
312               "Error: partial send of ICMP message\n");
313     }
314 }
315
316
317 /**
318  * Send an ICMP message to the target.
319  *
320  * @param my_ip source address
321  * @param other target address
322  */
323 static void
324 send_icmp (const struct in_addr *my_ip,
325            const struct in_addr *other)
326 {
327   struct ip_header ip_pkt;
328   struct icmp_ttl_exceeded_header icmp_ttl;
329   struct icmp_echo_header icmp_echo;
330   struct sockaddr_in dst;
331   char packet[sizeof (struct ip_header) * 2 +
332               sizeof (struct icmp_ttl_exceeded_header) +
333               sizeof (struct icmp_echo_header)];
334   size_t off;
335   int err;
336
337   /* ip header: send to (known) ip address */
338   off = 0;
339   ip_pkt.vers_ihl = 0x45;
340   ip_pkt.tos = 0;
341   ip_pkt.pkt_len = htons (sizeof (packet));
342   ip_pkt.id = htons (256); 
343   ip_pkt.flags_frag_offset = 0;
344   ip_pkt.ttl = IPDEFTTL;
345   ip_pkt.proto = IPPROTO_ICMP;
346   ip_pkt.checksum = 0; 
347   ip_pkt.src_ip = my_ip->s_addr;
348   ip_pkt.dst_ip = other->s_addr;
349   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, 
350                                         sizeof (struct ip_header)));
351   memcpy (&packet[off], 
352           &ip_pkt, 
353           sizeof (struct ip_header));
354   off = sizeof (ip_pkt);
355
356   /* icmp reply: time exceeded */
357   icmp_ttl.type = ICMP_TIME_EXCEEDED;
358   icmp_ttl.code = 0; 
359   icmp_ttl.checksum = 0;
360   icmp_ttl.unused = 0;
361   memcpy (&packet[off],
362           &icmp_ttl,
363           sizeof (struct icmp_ttl_exceeded_header));
364   off += sizeof (struct icmp_ttl_exceeded_header);
365
366   /* ip header of the presumably 'lost' udp packet */
367   ip_pkt.vers_ihl = 0x45;
368   ip_pkt.tos = 0;
369   ip_pkt.pkt_len = htons (sizeof (struct ip_header) + sizeof (struct icmp_echo_header));
370   ip_pkt.id = htons (256); 
371   ip_pkt.flags_frag_offset = 0;
372   ip_pkt.ttl = 1; /* real TTL would be 1 on a time exceeded packet */
373   ip_pkt.proto = IPPROTO_ICMP;
374   ip_pkt.src_ip = other->s_addr;
375   ip_pkt.dst_ip = dummy.s_addr;
376   ip_pkt.checksum = 0;
377   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt,
378                                         sizeof (struct ip_header)));  
379   memcpy (&packet[off], 
380           &ip_pkt, 
381           sizeof (struct ip_header));
382   off += sizeof (struct ip_header);
383
384   icmp_echo.type = ICMP_ECHO;
385   icmp_echo.code = 0;
386   icmp_echo.reserved = htonl (port);
387   icmp_echo.checksum = 0;
388   icmp_echo.checksum = htons(calc_checksum((uint16_t*) &icmp_echo, 
389                                            sizeof (struct icmp_echo_header)));
390   memcpy (&packet[off], 
391           &icmp_echo,
392           sizeof(struct icmp_echo_header));
393
394   /* no go back to calculate ICMP packet checksum */
395   off = sizeof (struct ip_header);
396   icmp_ttl.checksum = htons(calc_checksum((uint16_t*) &packet[off],
397                                           sizeof (struct icmp_ttl_exceeded_header) + 
398                                           sizeof (struct ip_header) + 
399                                           sizeof (struct icmp_echo_header)));
400   memcpy (&packet[off],
401           &icmp_ttl,
402           sizeof (struct icmp_ttl_exceeded_header));
403
404   /* prepare for transmission */
405   memset (&dst, 0, sizeof (dst));
406   dst.sin_family = AF_INET;
407 #if HAVE_SOCKADDR_IN_SIN_LEN
408   dst.sin_len = sizeof (struct sockaddr_in);
409 #endif
410   dst.sin_addr = *other;
411   err = sendto(rawsock, 
412                packet, 
413                sizeof (packet), 0, 
414                (struct sockaddr*)&dst, 
415                sizeof(dst));
416   if (err < 0) 
417     {
418       fprintf(stderr,
419               "sendto failed: %s\n", strerror(errno));
420     }
421   else if (sizeof (packet) != (size_t) err) 
422     {
423       fprintf(stderr,
424               "Error: partial send of ICMP message\n");
425     }
426 }
427
428
429 /**
430  * Create an ICMP raw socket for writing.
431  *
432  * @return -1 on error
433  */
434 static int
435 make_raw_socket ()
436 {
437   const int one = 1;
438   int ret;
439
440   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
441   if (-1 == ret)
442     {
443       fprintf (stderr,
444                "Error opening RAW socket: %s\n",
445                strerror (errno));
446       return -1;
447     }  
448   if (0 != setsockopt(ret, SOL_SOCKET, SO_BROADCAST,
449                       (char *)&one, sizeof(one)))
450     {
451       fprintf(stderr,
452               "setsockopt failed: %s\n",
453               strerror (errno));
454       close (ret);
455       return -1;
456     }
457   if (0 != setsockopt(ret, IPPROTO_IP, IP_HDRINCL,
458                       (char *)&one, sizeof(one)))
459     {
460       fprintf(stderr,
461               "setsockopt failed: %s\n",
462               strerror (errno));
463       close (ret);
464       return -1;
465     }
466   return ret;
467 }
468
469
470 int
471 main (int argc, char *const *argv)
472 {
473   struct in_addr external;
474   struct in_addr target;
475   uid_t uid;
476   unsigned int p;
477
478   if (4 != argc)
479     {
480       fprintf (stderr,
481                "This program must be started with our IP, the targets external IP, and our port as arguments.\n");
482       return 1;
483     }
484   if ( (1 != inet_pton (AF_INET, argv[1], &external)) ||
485        (1 != inet_pton (AF_INET, argv[2], &target)) )
486     {
487       fprintf (stderr,
488                "Error parsing IPv4 address: %s\n",
489                strerror (errno));
490       return 1;
491     }
492   if ( (1 != sscanf (argv[3], "%u", &p) ) ||
493        (0 == p) ||
494        (0xFFFF < p) )
495     {
496       fprintf (stderr,
497                "Error parsing port value `%s'\n",
498                argv[3]);
499       return 1;
500     }
501   port = (uint16_t) p;
502   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) 
503     {
504       fprintf (stderr,
505                "Internal error converting dummy IP to binary.\n");
506       return 2;
507     }
508   if (-1 == (rawsock = make_raw_socket()))
509     return 2;     
510   uid = getuid ();
511   if (0 != setresuid (uid, uid, uid))
512     {
513       fprintf (stderr,
514                "Failed to setresuid: %s\n",
515                strerror (errno));
516       /* not critical, continue anyway */
517     }
518   send_icmp (&external,
519              &target);
520   send_icmp_udp (&external,
521                  &target);
522   close (rawsock);
523   return 0;
524 }
525
526 /* end of gnunet-nat-client.c */