d4fc54b247d356d6587c8b33d4290121129201a3
[oweals/gnunet.git] / src / nat / gnunet-helper-nat-client.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2010 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14     
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 /**
20  * @file src/nat/gnunet-helper-nat-client.c
21  * @brief Tool to help bypass NATs using ICMP method; must run as root (SUID will do)
22  *        This code will work under GNU/Linux only.
23  * @author Christian Grothoff
24  *
25  * This program will send ONE ICMP message using RAW sockets
26  * to the IP address specified as the second argument.  Since
27  * it uses RAW sockets, it must be installed SUID or run as 'root'.
28  * In order to keep the security risk of the resulting SUID binary
29  * minimal, the program ONLY opens the RAW socket with root
30  * privileges, then drops them and only then starts to process
31  * command line arguments.  The code also does not link against
32  * any shared libraries (except libc) and is strictly minimal
33  * (except for checking for errors).  The following list of people
34  * have reviewed this code and considered it safe since the last
35  * modification (if you reviewed it, please have your name added
36  * to the list):
37  *
38  * - Christian Grothoff
39  * - Nathan Evans
40  * - Benjamin Kuperman (22 Aug 2010)
41  */
42 #if HAVE_CONFIG_H
43 /* Just needed for HAVE_SOCKADDR_IN_SIN_LEN test macro! */
44 #include "gnunet_config.h"
45 #else
46 #define _GNU_SOURCE
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 /* The following constant is missing from FreeBSD 9.2 */
63 #ifndef ICMP_TIME_EXCEEDED
64 #define ICMP_TIME_EXCEEDED 11
65 #endif
66
67 /**
68  * Call memcpy() but check for @a n being 0 first. In the latter
69  * case, it is now safe to pass NULL for @a src or @a dst.
70  * Unlike traditional memcpy(), returns nothing.
71  *
72  * @param dst destination of the copy, may be NULL if @a n is zero
73  * @param src source of the copy, may be NULL if @a n is zero
74  * @param n number of bytes to copy
75  */
76 #define GNUNET_memcpy(dst,src,n) do { if (0 != n) { (void) memcpy (dst,src,n); } } while (0)
77
78 /**
79  * Must match IP given in the server.
80  */
81 #define DUMMY_IP "192.0.2.86"
82
83 #define NAT_TRAV_PORT 22225
84
85 /**
86  * Must match packet ID used by gnunet-helper-nat-server.c
87  */
88 #define PACKET_ID 256
89
90 /**
91  * IPv4 header.
92  */
93 struct ip_header
94 {
95
96   /**
97    * Version (4 bits) + Internet header length (4 bits)
98    */
99   uint8_t vers_ihl;
100
101   /**
102    * Type of service
103    */
104   uint8_t tos;
105
106   /**
107    * Total length
108    */
109   uint16_t pkt_len;
110
111   /**
112    * Identification
113    */
114   uint16_t id;
115
116   /**
117    * Flags (3 bits) + Fragment offset (13 bits)
118    */
119   uint16_t flags_frag_offset;
120
121   /**
122    * Time to live
123    */
124   uint8_t ttl;
125
126   /**
127    * Protocol
128    */
129   uint8_t proto;
130
131   /**
132    * Header checksum
133    */
134   uint16_t checksum;
135
136   /**
137    * Source address
138    */
139   uint32_t src_ip;
140
141   /**
142    * Destination address
143    */
144   uint32_t dst_ip;
145 };
146
147 /**
148  * Format of ICMP packet.
149  */
150 struct icmp_ttl_exceeded_header
151 {
152   uint8_t type;
153
154   uint8_t code;
155
156   uint16_t checksum;
157
158   uint32_t unused;
159
160   /* followed by original payload */
161 };
162
163 struct icmp_echo_header
164 {
165   uint8_t type;
166
167   uint8_t code;
168
169   uint16_t checksum;
170
171   uint32_t reserved;
172 };
173
174 /**
175  * Beginning of UDP packet.
176  */
177 struct udp_header
178 {
179   uint16_t src_port;
180
181   uint16_t dst_port;
182
183   uint16_t length;
184
185   uint16_t crc;
186 };
187
188 /**
189  * Socket we use to send our fake ICMP replies.
190  */
191 static int rawsock;
192
193 /**
194  * Target "dummy" address of the packet we pretend to respond to.
195  */
196 static struct in_addr dummy;
197
198 /**
199  * Our "source" port.
200  */
201 static uint16_t port;
202
203
204 /**
205  * CRC-16 for IP/ICMP headers.
206  *
207  * @param data what to calculate the CRC over
208  * @param bytes number of bytes in data (must be multiple of 2)
209  * @return the CRC 16.
210  */
211 static uint16_t
212 calc_checksum (const uint16_t * data, unsigned int bytes)
213 {
214   uint32_t sum;
215   unsigned int i;
216
217   sum = 0;
218   for (i = 0; i < bytes / 2; i++)
219     sum += data[i];
220   sum = (sum & 0xffff) + (sum >> 16);
221   sum = htons (0xffff - sum);
222   return sum;
223 }
224
225
226 /**
227  * Send an ICMP message to the target.
228  *
229  * @param my_ip source address
230  * @param other target address
231  */
232 static void
233 send_icmp_udp (const struct in_addr *my_ip, const struct in_addr *other)
234 {
235   char packet[sizeof (struct ip_header) * 2 +
236               sizeof (struct icmp_ttl_exceeded_header) +
237               sizeof (struct udp_header)];
238   struct ip_header ip_pkt;
239   struct icmp_ttl_exceeded_header icmp_pkt;
240   struct udp_header udp_pkt;
241   struct sockaddr_in dst;
242   size_t off;
243   int err;
244
245   /* ip header: send to (known) ip address */
246   off = 0;
247   ip_pkt.vers_ihl = 0x45;
248   ip_pkt.tos = 0;
249 #ifdef FREEBSD
250   ip_pkt.pkt_len = sizeof (packet); /* Workaround PR kern/21737 */
251 #else
252   ip_pkt.pkt_len = htons (sizeof (packet));
253 #endif
254   ip_pkt.id = htons (PACKET_ID);
255   ip_pkt.flags_frag_offset = 0;
256   ip_pkt.ttl = 128;
257   ip_pkt.proto = IPPROTO_ICMP;
258   ip_pkt.checksum = 0;
259   ip_pkt.src_ip = my_ip->s_addr;
260   ip_pkt.dst_ip = other->s_addr;
261   ip_pkt.checksum =
262       htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header)));
263   GNUNET_memcpy (&packet[off],
264                  &ip_pkt,
265                  sizeof (struct ip_header));
266   off += sizeof (struct ip_header);
267
268   icmp_pkt.type = ICMP_TIME_EXCEEDED;
269   icmp_pkt.code = 0;
270   icmp_pkt.checksum = 0;
271   icmp_pkt.unused = 0;
272   GNUNET_memcpy (&packet[off],
273                  &icmp_pkt,
274                  sizeof (struct icmp_ttl_exceeded_header));
275   off += sizeof (struct icmp_ttl_exceeded_header);
276
277   /* ip header of the presumably 'lost' udp packet */
278   ip_pkt.vers_ihl = 0x45;
279   ip_pkt.tos = 0;
280   ip_pkt.pkt_len =
281       htons (sizeof (struct ip_header) + sizeof (struct udp_header));
282   ip_pkt.id = htons (0);
283   ip_pkt.flags_frag_offset = 0;
284   ip_pkt.ttl = 128;
285   ip_pkt.proto = IPPROTO_UDP;
286   ip_pkt.checksum = 0;
287   ip_pkt.src_ip = other->s_addr;
288   ip_pkt.dst_ip = dummy.s_addr;
289   ip_pkt.checksum =
290       htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header)));
291   GNUNET_memcpy (&packet[off],
292                  &ip_pkt,
293                  sizeof (struct ip_header));
294   off += sizeof (struct ip_header);
295
296   /* build UDP header */
297   udp_pkt.src_port = htons (NAT_TRAV_PORT);
298   udp_pkt.dst_port = htons (NAT_TRAV_PORT);
299   udp_pkt.length = htons (port);
300   udp_pkt.crc = 0;
301   GNUNET_memcpy (&packet[off],
302                  &udp_pkt,
303                  sizeof (struct udp_header));
304   off += sizeof (struct udp_header);
305
306   /* set ICMP checksum */
307   icmp_pkt.checksum =
308       htons (calc_checksum
309              ((uint16_t *) & packet[sizeof (struct ip_header)],
310               sizeof (struct icmp_ttl_exceeded_header) +
311               sizeof (struct ip_header) + sizeof (struct udp_header)));
312   GNUNET_memcpy (&packet[sizeof (struct ip_header)],
313                  &icmp_pkt,
314                  sizeof (struct icmp_ttl_exceeded_header));
315
316   memset (&dst, 0, sizeof (dst));
317   dst.sin_family = AF_INET;
318 #if HAVE_SOCKADDR_IN_SIN_LEN
319   dst.sin_len = sizeof (struct sockaddr_in);
320 #endif
321   dst.sin_addr = *other;
322   err =
323       sendto (rawsock, packet, sizeof (packet), 0, (struct sockaddr *) &dst,
324               sizeof (dst));
325   if (err < 0)
326   {
327     fprintf (stderr, "sendto failed: %s\n", strerror (errno));
328   }
329   else if (sizeof (packet) != (size_t) err)
330   {
331     fprintf (stderr, "Error: partial send of ICMP message with size %lu\n", (unsigned long) off);
332   }
333 }
334
335
336 /**
337  * Send an ICMP message to the target.
338  *
339  * @param my_ip source address
340  * @param other target address
341  */
342 static void
343 send_icmp (const struct in_addr *my_ip, const struct in_addr *other)
344 {
345   struct ip_header ip_pkt;
346   struct icmp_ttl_exceeded_header icmp_ttl;
347   struct icmp_echo_header icmp_echo;
348   struct sockaddr_in dst;
349   char packet[sizeof (struct ip_header) * 2 +
350               sizeof (struct icmp_ttl_exceeded_header) +
351               sizeof (struct icmp_echo_header)];
352   size_t off;
353   int err;
354
355   /* ip header: send to (known) ip address */
356   off = 0;
357   ip_pkt.vers_ihl = 0x45;
358   ip_pkt.tos = 0;
359 #ifdef FREEBSD
360   ip_pkt.pkt_len = sizeof (packet); /* Workaround PR kern/21737 */
361 #else
362   ip_pkt.pkt_len = htons (sizeof (packet));
363 #endif
364   ip_pkt.id = htons (PACKET_ID);
365   ip_pkt.flags_frag_offset = 0;
366   ip_pkt.ttl = IPDEFTTL;
367   ip_pkt.proto = IPPROTO_ICMP;
368   ip_pkt.checksum = 0;
369   ip_pkt.src_ip = my_ip->s_addr;
370   ip_pkt.dst_ip = other->s_addr;
371   ip_pkt.checksum =
372       htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header)));
373   GNUNET_memcpy (&packet[off],
374                  &ip_pkt,
375                  sizeof (struct ip_header));
376   off = sizeof (ip_pkt);
377
378   /* icmp reply: time exceeded */
379   icmp_ttl.type = ICMP_TIME_EXCEEDED;
380   icmp_ttl.code = 0;
381   icmp_ttl.checksum = 0;
382   icmp_ttl.unused = 0;
383   GNUNET_memcpy (&packet[off],
384                  &icmp_ttl,
385                  sizeof (struct icmp_ttl_exceeded_header));
386   off += sizeof (struct icmp_ttl_exceeded_header);
387
388   /* ip header of the presumably 'lost' udp packet */
389   ip_pkt.vers_ihl = 0x45;
390   ip_pkt.tos = 0;
391   ip_pkt.pkt_len =
392       htons (sizeof (struct ip_header) + sizeof (struct icmp_echo_header));
393   ip_pkt.id = htons (PACKET_ID);
394   ip_pkt.flags_frag_offset = 0;
395   ip_pkt.ttl = 1;               /* real TTL would be 1 on a time exceeded packet */
396   ip_pkt.proto = IPPROTO_ICMP;
397   ip_pkt.src_ip = other->s_addr;
398   ip_pkt.dst_ip = dummy.s_addr;
399   ip_pkt.checksum = 0;
400   ip_pkt.checksum =
401       htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header)));
402   GNUNET_memcpy (&packet[off],
403                  &ip_pkt,
404                  sizeof (struct ip_header));
405   off += sizeof (struct ip_header);
406
407   icmp_echo.type = ICMP_ECHO;
408   icmp_echo.code = 0;
409   icmp_echo.reserved = htonl (port);
410   icmp_echo.checksum = 0;
411   icmp_echo.checksum =
412       htons (calc_checksum
413              ((uint16_t *) &icmp_echo, sizeof (struct icmp_echo_header)));
414   GNUNET_memcpy (&packet[off],
415                  &icmp_echo,
416                  sizeof (struct icmp_echo_header));
417
418   /* no go back to calculate ICMP packet checksum */
419   off = sizeof (struct ip_header);
420   icmp_ttl.checksum =
421       htons (calc_checksum
422              ((uint16_t *) & packet[off],
423               sizeof (struct icmp_ttl_exceeded_header) +
424               sizeof (struct ip_header) + sizeof (struct icmp_echo_header)));
425   GNUNET_memcpy (&packet[off],
426                  &icmp_ttl,
427                  sizeof (struct icmp_ttl_exceeded_header));
428
429   /* prepare for transmission */
430   memset (&dst, 0, sizeof (dst));
431   dst.sin_family = AF_INET;
432 #if HAVE_SOCKADDR_IN_SIN_LEN
433   dst.sin_len = sizeof (struct sockaddr_in);
434 #endif
435   dst.sin_addr = *other;
436   err =
437       sendto (rawsock, packet, sizeof (packet), 0, (struct sockaddr *) &dst,
438               sizeof (dst));
439   if (err < 0)
440   {
441     fprintf (stderr, "sendto failed: %s\n", strerror (errno));
442   }
443   else if (sizeof (packet) != (size_t) err)
444   {
445     fprintf (stderr, "Error: partial send of ICMP message\n");
446   }
447 }
448
449
450 int
451 main (int argc, char *const *argv)
452 {
453   const int one = 1;
454   struct in_addr external;
455   struct in_addr target;
456   uid_t uid;
457   unsigned int p;
458   int raw_eno;
459   int global_ret;
460
461   /* Create an ICMP raw socket for writing (only operation that requires root) */
462   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
463   raw_eno = errno; /* for later error checking */
464
465   /* now drop root privileges */
466   uid = getuid ();
467 #ifdef HAVE_SETRESUID
468   if (0 != setresuid (uid, uid, uid))
469   {
470     fprintf (stderr, "Failed to setresuid: %s\n", strerror (errno));
471     global_ret = 1;
472     goto cleanup;
473   }
474 #else
475   if (0 != (setuid (uid) | seteuid (uid)))
476   {
477     fprintf (stderr, "Failed to setuid: %s\n", strerror (errno));
478     global_ret = 2;
479     goto cleanup;
480   }
481 #endif
482   if (-1 == rawsock)
483   {
484     fprintf (stderr, "Error opening RAW socket: %s\n", strerror (raw_eno));
485     global_ret = 3;
486     goto cleanup;
487   }
488   if (0 !=
489       setsockopt (rawsock, SOL_SOCKET, SO_BROADCAST, (char *) &one, sizeof (one)))
490   {
491     fprintf (stderr, "setsockopt failed: %s\n", strerror (errno));
492     global_ret = 4;
493     goto cleanup;
494   }
495   if (0 !=
496       setsockopt (rawsock, IPPROTO_IP, IP_HDRINCL, (char *) &one, sizeof (one)))
497   {
498     fprintf (stderr, "setsockopt failed: %s\n", strerror (errno));
499     global_ret = 5;
500     goto cleanup;
501   }
502
503   if (4 != argc)
504   {
505     fprintf (stderr,
506              "This program must be started with our IP, the targets external IP, and our port as arguments.\n");
507     global_ret = 6;
508     goto cleanup;
509   }
510   if ((1 != inet_pton (AF_INET, argv[1], &external)) ||
511       (1 != inet_pton (AF_INET, argv[2], &target)))
512   {
513     fprintf (stderr, "Error parsing IPv4 address: %s\n", strerror (errno));
514     global_ret = 7;
515     goto cleanup;
516   }
517   if ((1 != sscanf (argv[3], "%u", &p)) || (0 == p) || (0xFFFF < p))
518   {
519     fprintf (stderr, "Error parsing port value `%s'\n", argv[3]);
520     global_ret = 8;
521     goto cleanup;
522   }
523   port = (uint16_t) p;
524   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy))
525   {
526     fprintf (stderr, "Internal error converting dummy IP to binary.\n");
527     global_ret = 9;
528     goto cleanup;
529   }
530   send_icmp (&external, &target);
531   send_icmp_udp (&external, &target);
532   global_ret = 0;
533  cleanup:
534   if (-1 != rawsock)
535     (void) close (rawsock);
536   return global_ret;
537 }
538
539 /* end of gnunet-helper-nat-client.c */