fix
[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_packet 
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_packet 
131 {
132   uint8_t type;
133
134   uint8_t code;
135
136   uint16_t checksum;
137
138   uint32_t reserved;
139 };
140
141 struct icmp_echo_packet
142 {
143   uint8_t type;
144
145   uint8_t code;
146
147   uint16_t checksum;
148
149   uint32_t reserved;
150
151   uint32_t data;
152 };
153
154 /**
155  * Beginning of UDP packet.
156  */
157 struct udp_packet
158 {
159   uint16_t src_port;
160
161   uint16_t dst_port;
162
163   uint32_t length;
164 };
165
166 /**
167  * Socket we use to send our fake ICMP replies.
168  */
169 static int rawsock;
170
171 /**
172  * Target "dummy" address of the packet we pretend to respond to.
173  */
174 static struct in_addr dummy;
175  
176 /**
177  * Our "source" port.
178  */
179 static uint16_t port;
180
181
182 /**
183  * CRC-16 for IP/ICMP headers.
184  *
185  * @param data what to calculate the CRC over
186  * @param bytes number of bytes in data (must be multiple of 2)
187  * @return the CRC 16.
188  */
189 static uint16_t 
190 calc_checksum(const uint16_t *data, 
191               unsigned int bytes)
192 {
193   uint32_t sum;
194   unsigned int i;
195
196   sum = 0;
197   for (i=0;i<bytes/2;i++) 
198     sum += data[i];        
199   sum = (sum & 0xffff) + (sum >> 16);
200   sum = htons(0xffff - sum);
201   return sum;
202 }
203
204
205 /**
206  * Send an ICMP message to the target.
207  *
208  * @param my_ip source address
209  * @param other target address
210  */
211 static void
212 send_icmp_udp (const struct in_addr *my_ip,
213                const struct in_addr *other)
214 {
215   struct ip_packet ip_pkt;
216   struct icmp_packet icmp_pkt;
217   struct udp_packet udp_pkt;
218
219   struct sockaddr_in dst;
220   char packet[sizeof(ip_pkt) * 2 + sizeof(icmp_pkt) * 2 + sizeof(uint32_t)];
221
222   size_t off;
223   int err;
224
225   /* ip header: send to (known) ip address */
226   off = 0;
227   memset(&ip_pkt, 0, sizeof(ip_pkt));
228   ip_pkt.vers_ihl = 0x45;
229   ip_pkt.tos = 0;
230   ip_pkt.pkt_len = htons(sizeof (packet));
231   ip_pkt.id = htons(256);
232   ip_pkt.flags_frag_offset = 0;
233   ip_pkt.ttl = 128;
234   ip_pkt.proto = IPPROTO_ICMP;
235   ip_pkt.checksum = 0;
236   ip_pkt.src_ip = my_ip->s_addr;
237   ip_pkt.dst_ip = other->s_addr;
238   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
239   memcpy(&packet[off], &ip_pkt, sizeof(ip_pkt));
240   off += sizeof(ip_pkt);
241
242   /* ip header of the presumably 'lost' udp packet */
243   ip_pkt.vers_ihl = 0x45;
244   ip_pkt.tos = 0;
245   ip_pkt.pkt_len = (sizeof (struct ip_packet) + sizeof (struct icmp_echo_packet));
246
247   icmp_pkt.type = 11; /* TTL exceeded */
248   icmp_pkt.code = 0;
249   icmp_pkt.checksum = 0;
250   icmp_pkt.reserved = 0;
251   memcpy(&packet[off], &icmp_pkt, sizeof(icmp_pkt));
252   off += sizeof(icmp_pkt);
253
254   /* build inner IP header */
255   memset(&ip_pkt, 0, sizeof(ip_pkt));
256   ip_pkt.vers_ihl = 0x45;
257   ip_pkt.tos = 0;
258   ip_pkt.pkt_len = htons(sizeof (ip_pkt) + sizeof(udp_pkt));
259   ip_pkt.id = htons(0);
260   ip_pkt.flags_frag_offset = 0;
261   ip_pkt.ttl = 128;
262   ip_pkt.proto = IPPROTO_UDP;
263   ip_pkt.checksum = 0;
264   ip_pkt.src_ip = other->s_addr;
265   ip_pkt.dst_ip = dummy.s_addr;
266   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
267   memcpy(&packet[off], &ip_pkt, sizeof(ip_pkt));
268   off += sizeof(ip_pkt);
269
270   /* build UDP header */
271   udp_pkt.src_port = htons(NAT_TRAV_PORT);
272   udp_pkt.dst_port = htons(NAT_TRAV_PORT);
273
274   memset(&udp_pkt.length, 0, sizeof(uint32_t));
275   udp_pkt.length = htons (port);
276   memcpy(&packet[off], &udp_pkt, sizeof(udp_pkt));
277   off += sizeof(udp_pkt);
278
279   /* set ICMP checksum */
280   icmp_pkt.checksum = htons(calc_checksum((uint16_t*)&packet[sizeof(ip_pkt)],
281                             sizeof (icmp_pkt) + sizeof(ip_pkt) + sizeof(udp_pkt)));
282   memcpy (&packet[sizeof(ip_pkt)], &icmp_pkt, sizeof (icmp_pkt));
283
284
285   memset (&dst, 0, sizeof (dst));
286   dst.sin_family = AF_INET;
287   dst.sin_addr = *other;
288   err = sendto(rawsock,
289                packet,
290                off, 0,
291                (struct sockaddr*)&dst,
292                sizeof(dst));
293
294   if (err < 0)
295     {
296       fprintf(stderr,
297               "sendto failed: %s\n", strerror(errno));
298     }
299   else if (err != off)
300     {
301       fprintf(stderr,
302               "Error: partial send of ICMP message\n");
303     }
304 }
305
306
307 /**
308  * Send an ICMP message to the target.
309  *
310  * @param my_ip source address
311  * @param other target address
312  */
313 static void
314 send_icmp (const struct in_addr *my_ip,
315            const struct in_addr *other)
316 {
317   struct ip_packet ip_pkt;
318   struct icmp_packet icmp_pkt;
319   struct icmp_echo_packet icmp_echo;
320   struct sockaddr_in dst;
321   char packet[sizeof (struct ip_packet)*2 + sizeof (struct icmp_packet) + sizeof(struct icmp_echo_packet)];
322
323   size_t off;
324   int err;
325
326   /* ip header: send to (known) ip address */
327   off = 0;
328   ip_pkt.vers_ihl = 0x45;
329   ip_pkt.tos = 0;
330   ip_pkt.pkt_len = sizeof (packet); /* huh? */
331   ip_pkt.id = 1; 
332   ip_pkt.flags_frag_offset = 0;
333   ip_pkt.ttl = IPDEFTTL;
334   ip_pkt.proto = IPPROTO_ICMP;
335   ip_pkt.checksum = 0; 
336   ip_pkt.src_ip = my_ip->s_addr;
337   ip_pkt.dst_ip = other->s_addr;
338   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (struct ip_packet)));
339   memcpy (&packet[off], &ip_pkt, sizeof (struct ip_packet));
340   off = sizeof (ip_pkt);
341
342   /* icmp reply: time exceeded */
343   icmp_pkt.type = ICMP_TIME_EXCEEDED;
344   icmp_pkt.code = 0; 
345   icmp_pkt.reserved = 0;
346   icmp_pkt.checksum = 0;
347   memcpy (&packet[off],
348           &icmp_pkt,
349           sizeof (struct icmp_packet));
350   off += sizeof (struct icmp_packet);
351
352   /* ip header of the presumably 'lost' udp packet */
353   ip_pkt.vers_ihl = 0x45;
354   ip_pkt.tos = 0;
355   ip_pkt.pkt_len = (sizeof (struct ip_packet) + sizeof (struct icmp_echo_packet));
356   ip_pkt.id = 1; 
357   ip_pkt.flags_frag_offset = 0;
358   ip_pkt.ttl = 1; /* real TTL would be 1 on a time exceeded packet */
359   ip_pkt.proto = IPPROTO_ICMP;
360   ip_pkt.src_ip = other->s_addr;
361   ip_pkt.dst_ip = dummy.s_addr;
362   ip_pkt.checksum = 0;
363   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (struct ip_packet)));  
364   memcpy (&packet[off], &ip_pkt, sizeof (struct ip_packet));
365   off += sizeof (struct ip_packet);
366
367   icmp_echo.type = ICMP_ECHO;
368   icmp_echo.code = 0;
369   icmp_echo.reserved = 0;
370   icmp_echo.checksum = 0;
371   icmp_echo.data = htons(port);
372   icmp_echo.checksum = htons(calc_checksum((uint16_t*) &icmp_echo, 
373                                            sizeof (struct icmp_echo_packet)));
374   memcpy (&packet[off], 
375           &icmp_echo,
376           sizeof(struct icmp_echo_packet));
377
378   /* no go back to calculate ICMP packet checksum */
379   off = sizeof (ip_pkt);
380   icmp_pkt.checksum = htons(calc_checksum((uint16_t*) &packet[off],
381                                           sizeof (struct icmp_packet) + sizeof(struct ip_packet) + sizeof(struct icmp_echo_packet)));
382   memcpy (&packet[off],
383           &icmp_pkt,
384           sizeof (struct icmp_packet));
385
386   /* prepare for transmission */
387   memset (&dst, 0, sizeof (dst));
388   dst.sin_family = AF_INET;
389 #if HAVE_SOCKADDR_IN_SIN_LEN
390   dst.sin_len = sizeof (struct sockaddr_in);
391 #endif
392   dst.sin_addr = *other;
393   err = sendto(rawsock, 
394                packet, 
395                sizeof (packet), 0, 
396                (struct sockaddr*)&dst, 
397                sizeof(struct sockaddr_in));
398   if (err < 0) 
399     {
400       fprintf(stderr,
401               "sendto failed: %s\n", strerror(errno));
402     }
403   else if (err != sizeof (packet)) 
404     {
405       fprintf(stderr,
406               "Error: partial send of ICMP message\n");
407     }
408 }
409
410
411 /**
412  * Create an ICMP raw socket for writing.
413  *
414  * @return -1 on error
415  */
416 static int
417 make_raw_socket ()
418 {
419   const int one = 1;
420   int ret;
421
422   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
423   if (-1 == ret)
424     {
425       fprintf (stderr,
426                "Error opening RAW socket: %s\n",
427                strerror (errno));
428       return -1;
429     }  
430   if (setsockopt(ret, SOL_SOCKET, SO_BROADCAST,
431                  (char *)&one, sizeof(one)) == -1)
432     {
433       fprintf(stderr,
434               "setsockopt failed: %s\n",
435               strerror (errno));
436       close (ret);
437       return -1;
438     }
439   if (setsockopt(ret, IPPROTO_IP, IP_HDRINCL,
440                  (char *)&one, sizeof(one)) == -1)
441     {
442       fprintf(stderr,
443               "setsockopt failed: %s\n",
444               strerror (errno));
445       close (ret);
446       return -1;
447     }
448   return ret;
449 }
450
451
452 int
453 main (int argc, char *const *argv)
454 {
455   struct in_addr external;
456   struct in_addr target;
457   uid_t uid;
458   unsigned int p;
459
460   if (argc != 4)
461     {
462       fprintf (stderr,
463                "This program must be started with our IP, the targets external IP, and our port as arguments.\n");
464       return 1;
465     }
466   if ( (1 != inet_pton (AF_INET, argv[1], &external)) ||
467        (1 != inet_pton (AF_INET, argv[2], &target)) )
468     {
469       fprintf (stderr,
470                "Error parsing IPv4 address: %s\n",
471                strerror (errno));
472       return 1;
473     }
474   if ( (1 != sscanf (argv[3], "%u", &p) ) ||
475        (p == 0) ||
476        (p > 0xFFFF) )
477     {
478       fprintf (stderr,
479                "Error parsing port value `%s'\n",
480                argv[3]);
481       return 1;
482     }
483   port = (uint16_t) p;
484   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) 
485     {
486       fprintf (stderr,
487                "Internal error converting dummy IP to binary.\n");
488       return 2;
489     }
490   if (-1 == (rawsock = make_raw_socket()))
491     return 2;     
492   uid = getuid ();
493   if (0 != setresuid (uid, uid, uid))
494     {
495       fprintf (stderr,
496                "Failed to setresuid: %s\n",
497                strerror (errno));
498       /* not critical, continue anyway */
499     }
500   send_icmp (&external,
501              &target);
502   send_icmp_udp (&external,
503                  &target);
504   close (rawsock);
505   return 0;
506 }
507
508 /* end of gnunet-nat-client.c */