get rid of plain memcpy calls
[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
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   GNUNET_memcpy (&packet[off],
255                  &ip_pkt,
256                  sizeof (struct ip_header));
257   off += sizeof (struct ip_header);
258
259   icmp_pkt.type = ICMP_TIME_EXCEEDED;
260   icmp_pkt.code = 0;
261   icmp_pkt.checksum = 0;
262   icmp_pkt.unused = 0;
263   GNUNET_memcpy (&packet[off],
264                  &icmp_pkt,
265                  sizeof (struct icmp_ttl_exceeded_header));
266   off += sizeof (struct icmp_ttl_exceeded_header);
267
268   /* ip header of the presumably 'lost' udp packet */
269   ip_pkt.vers_ihl = 0x45;
270   ip_pkt.tos = 0;
271   ip_pkt.pkt_len =
272       htons (sizeof (struct ip_header) + sizeof (struct udp_header));
273   ip_pkt.id = htons (0);
274   ip_pkt.flags_frag_offset = 0;
275   ip_pkt.ttl = 128;
276   ip_pkt.proto = IPPROTO_UDP;
277   ip_pkt.checksum = 0;
278   ip_pkt.src_ip = other->s_addr;
279   ip_pkt.dst_ip = dummy.s_addr;
280   ip_pkt.checksum =
281       htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header)));
282   GNUNET_memcpy (&packet[off],
283                  &ip_pkt,
284                  sizeof (struct ip_header));
285   off += sizeof (struct ip_header);
286
287   /* build UDP header */
288   udp_pkt.src_port = htons (NAT_TRAV_PORT);
289   udp_pkt.dst_port = htons (NAT_TRAV_PORT);
290   udp_pkt.length = htons (port);
291   udp_pkt.crc = 0;
292   GNUNET_memcpy (&packet[off],
293                  &udp_pkt,
294                  sizeof (struct udp_header));
295   off += sizeof (struct udp_header);
296
297   /* set ICMP checksum */
298   icmp_pkt.checksum =
299       htons (calc_checksum
300              ((uint16_t *) & packet[sizeof (struct ip_header)],
301               sizeof (struct icmp_ttl_exceeded_header) +
302               sizeof (struct ip_header) + sizeof (struct udp_header)));
303   GNUNET_memcpy (&packet[sizeof (struct ip_header)],
304                  &icmp_pkt,
305                  sizeof (struct icmp_ttl_exceeded_header));
306
307   memset (&dst, 0, sizeof (dst));
308   dst.sin_family = AF_INET;
309 #if HAVE_SOCKADDR_IN_SIN_LEN
310   dst.sin_len = sizeof (struct sockaddr_in);
311 #endif
312   dst.sin_addr = *other;
313   err =
314       sendto (rawsock, packet, sizeof (packet), 0, (struct sockaddr *) &dst,
315               sizeof (dst));
316   if (err < 0)
317   {
318     fprintf (stderr, "sendto failed: %s\n", strerror (errno));
319   }
320   else if (sizeof (packet) != (size_t) err)
321   {
322     fprintf (stderr, "Error: partial send of ICMP message with size %lu\n", (unsigned long) off);
323   }
324 }
325
326
327 /**
328  * Send an ICMP message to the target.
329  *
330  * @param my_ip source address
331  * @param other target address
332  */
333 static void
334 send_icmp (const struct in_addr *my_ip, const struct in_addr *other)
335 {
336   struct ip_header ip_pkt;
337   struct icmp_ttl_exceeded_header icmp_ttl;
338   struct icmp_echo_header icmp_echo;
339   struct sockaddr_in dst;
340   char packet[sizeof (struct ip_header) * 2 +
341               sizeof (struct icmp_ttl_exceeded_header) +
342               sizeof (struct icmp_echo_header)];
343   size_t off;
344   int err;
345
346   /* ip header: send to (known) ip address */
347   off = 0;
348   ip_pkt.vers_ihl = 0x45;
349   ip_pkt.tos = 0;
350 #ifdef FREEBSD
351   ip_pkt.pkt_len = sizeof (packet); /* Workaround PR kern/21737 */
352 #else
353   ip_pkt.pkt_len = htons (sizeof (packet));
354 #endif
355   ip_pkt.id = htons (PACKET_ID);
356   ip_pkt.flags_frag_offset = 0;
357   ip_pkt.ttl = IPDEFTTL;
358   ip_pkt.proto = IPPROTO_ICMP;
359   ip_pkt.checksum = 0;
360   ip_pkt.src_ip = my_ip->s_addr;
361   ip_pkt.dst_ip = other->s_addr;
362   ip_pkt.checksum =
363       htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header)));
364   GNUNET_memcpy (&packet[off],
365                  &ip_pkt,
366                  sizeof (struct ip_header));
367   off = sizeof (ip_pkt);
368
369   /* icmp reply: time exceeded */
370   icmp_ttl.type = ICMP_TIME_EXCEEDED;
371   icmp_ttl.code = 0;
372   icmp_ttl.checksum = 0;
373   icmp_ttl.unused = 0;
374   GNUNET_memcpy (&packet[off],
375                  &icmp_ttl,
376                  sizeof (struct icmp_ttl_exceeded_header));
377   off += sizeof (struct icmp_ttl_exceeded_header);
378
379   /* ip header of the presumably 'lost' udp packet */
380   ip_pkt.vers_ihl = 0x45;
381   ip_pkt.tos = 0;
382   ip_pkt.pkt_len =
383       htons (sizeof (struct ip_header) + sizeof (struct icmp_echo_header));
384   ip_pkt.id = htons (PACKET_ID);
385   ip_pkt.flags_frag_offset = 0;
386   ip_pkt.ttl = 1;               /* real TTL would be 1 on a time exceeded packet */
387   ip_pkt.proto = IPPROTO_ICMP;
388   ip_pkt.src_ip = other->s_addr;
389   ip_pkt.dst_ip = dummy.s_addr;
390   ip_pkt.checksum = 0;
391   ip_pkt.checksum =
392       htons (calc_checksum ((uint16_t *) & ip_pkt, sizeof (struct ip_header)));
393   GNUNET_memcpy (&packet[off],
394                  &ip_pkt,
395                  sizeof (struct ip_header));
396   off += sizeof (struct ip_header);
397
398   icmp_echo.type = ICMP_ECHO;
399   icmp_echo.code = 0;
400   icmp_echo.reserved = htonl (port);
401   icmp_echo.checksum = 0;
402   icmp_echo.checksum =
403       htons (calc_checksum
404              ((uint16_t *) &icmp_echo, sizeof (struct icmp_echo_header)));
405   GNUNET_memcpy (&packet[off],
406                  &icmp_echo,
407                  sizeof (struct icmp_echo_header));
408
409   /* no go back to calculate ICMP packet checksum */
410   off = sizeof (struct ip_header);
411   icmp_ttl.checksum =
412       htons (calc_checksum
413              ((uint16_t *) & packet[off],
414               sizeof (struct icmp_ttl_exceeded_header) +
415               sizeof (struct ip_header) + sizeof (struct icmp_echo_header)));
416   GNUNET_memcpy (&packet[off],
417                  &icmp_ttl,
418                  sizeof (struct icmp_ttl_exceeded_header));
419
420   /* prepare for transmission */
421   memset (&dst, 0, sizeof (dst));
422   dst.sin_family = AF_INET;
423 #if HAVE_SOCKADDR_IN_SIN_LEN
424   dst.sin_len = sizeof (struct sockaddr_in);
425 #endif
426   dst.sin_addr = *other;
427   err =
428       sendto (rawsock, packet, sizeof (packet), 0, (struct sockaddr *) &dst,
429               sizeof (dst));
430   if (err < 0)
431   {
432     fprintf (stderr, "sendto failed: %s\n", strerror (errno));
433   }
434   else if (sizeof (packet) != (size_t) err)
435   {
436     fprintf (stderr, "Error: partial send of ICMP message\n");
437   }
438 }
439
440
441 int
442 main (int argc, char *const *argv)
443 {
444   const int one = 1;
445   struct in_addr external;
446   struct in_addr target;
447   uid_t uid;
448   unsigned int p;
449   int raw_eno;
450   int global_ret;
451
452   /* Create an ICMP raw socket for writing (only operation that requires root) */
453   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
454   raw_eno = errno; /* for later error checking */
455
456   /* now drop root privileges */
457   uid = getuid ();
458 #ifdef HAVE_SETRESUID
459   if (0 != setresuid (uid, uid, uid))
460   {
461     fprintf (stderr, "Failed to setresuid: %s\n", strerror (errno));
462     global_ret = 1;
463     goto cleanup;
464   }
465 #else
466   if (0 != (setuid (uid) | seteuid (uid)))
467   {
468     fprintf (stderr, "Failed to setuid: %s\n", strerror (errno));
469     global_ret = 2;
470     goto cleanup;
471   }
472 #endif
473   if (-1 == rawsock)
474   {
475     fprintf (stderr, "Error opening RAW socket: %s\n", strerror (raw_eno));
476     global_ret = 3;
477     goto cleanup;
478   }
479   if (0 !=
480       setsockopt (rawsock, SOL_SOCKET, SO_BROADCAST, (char *) &one, sizeof (one)))
481   {
482     fprintf (stderr, "setsockopt failed: %s\n", strerror (errno));
483     global_ret = 4;
484     goto cleanup;
485   }
486   if (0 !=
487       setsockopt (rawsock, IPPROTO_IP, IP_HDRINCL, (char *) &one, sizeof (one)))
488   {
489     fprintf (stderr, "setsockopt failed: %s\n", strerror (errno));
490     global_ret = 5;
491     goto cleanup;
492   }
493
494   if (4 != argc)
495   {
496     fprintf (stderr,
497              "This program must be started with our IP, the targets external IP, and our port as arguments.\n");
498     global_ret = 6;
499     goto cleanup;
500   }
501   if ((1 != inet_pton (AF_INET, argv[1], &external)) ||
502       (1 != inet_pton (AF_INET, argv[2], &target)))
503   {
504     fprintf (stderr, "Error parsing IPv4 address: %s\n", strerror (errno));
505     global_ret = 7;
506     goto cleanup;
507   }
508   if ((1 != sscanf (argv[3], "%u", &p)) || (0 == p) || (0xFFFF < p))
509   {
510     fprintf (stderr, "Error parsing port value `%s'\n", argv[3]);
511     global_ret = 8;
512     goto cleanup;
513   }
514   port = (uint16_t) p;
515   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy))
516   {
517     fprintf (stderr, "Internal error converting dummy IP to binary.\n");
518     global_ret = 9;
519     goto cleanup;
520   }
521   send_icmp (&external, &target);
522   send_icmp_udp (&external, &target);
523   global_ret = 0;
524  cleanup:
525   if (-1 != rawsock)
526     (void) close (rawsock);
527   return global_ret;
528 }
529
530 /* end of gnunet-helper-nat-client.c */