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