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