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