indentation
[oweals/gnunet.git] / src / nat / gnunet-helper-nat-client-windows.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/nat/gnunet-helper-nat-client-windows.c
23  * @brief Tool to help bypass NATs using ICMP method; must run as
24  *        administrator on W32
25  *        This code is forx W32.
26  * @author Nathan Evans
27  *
28  * This program will send ONE ICMP message using RAW sockets
29  * to the IP address specified as the second argument.  Since
30  * it uses RAW sockets, it must be installed SUID or run as 'root'.
31  * In order to keep the security risk of the resulting SUID binary
32  * minimal, the program ONLY opens the RAW socket with root
33  * privileges, then drops them and only then starts to process
34  * command line arguments.  The code also does not link against
35  * any shared libraries (except libc) and is strictly minimal
36  * (except for checking for errors).  The following list of people
37  * have reviewed this code and considered it safe since the last
38  * modification (if you reviewed it, please have your name added
39  * to the list):
40  *
41  * - Christian Grothoff
42  * - Nathan Evans
43  */
44 #define _GNU_SOURCE
45
46 #include <winsock2.h>
47 #include <ws2tcpip.h>
48 #include <sys/time.h>
49 #include <sys/types.h>
50 #include <unistd.h>
51 #include <stdio.h>
52 #include <string.h>
53 #include <errno.h>
54 #include <stdlib.h>
55 #include <stdint.h>
56 #include <time.h>
57
58
59 #define ICMP_ECHO 8
60 #define IPDEFTTL 64
61 #define ICMP_TIME_EXCEEDED 11
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_header
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 /**
129  * Format of ICMP packet.
130  */
131 struct icmp_ttl_exceeded_header
132 {
133   uint8_t type;
134
135   uint8_t code;
136
137   uint16_t checksum;
138
139   uint32_t unused;
140
141   /* followed by original payload */
142 };
143
144 struct icmp_echo_header
145 {
146   uint8_t type;
147
148   uint8_t code;
149
150   uint16_t checksum;
151
152   uint32_t reserved;
153 };
154
155 /**
156  * Beginning of UDP packet.
157  */
158 struct udp_header
159 {
160   uint16_t src_port;
161
162   uint16_t dst_port;
163
164   uint16_t length;
165
166   uint16_t crc;
167 };
168
169
170 /**
171  * Socket we use to send our ICMP packets.
172  */
173 static SOCKET rawsock;
174
175 /**
176  * Target "dummy" address.
177  */
178 static struct in_addr dummy;
179
180 /**
181  * Port we are listening on (communicated to the server).
182  */
183 static uint16_t port;
184
185
186
187 /**
188  * Convert IPv4 address from text to binary form.
189  *
190  * @param af address family
191  * @param cp the address to print
192  * @param buf where to write the address result
193  * @return 1 on success
194  */
195 static int
196 inet_pton (int af, const char *cp, struct in_addr *buf)
197 {
198   buf->s_addr = inet_addr (cp);
199   if (buf->s_addr == INADDR_NONE)
200   {
201     fprintf (stderr, "Error %d handling address %s", WSAGetLastError (), cp);
202     return 0;
203   }
204   return 1;
205 }
206
207
208 /**
209  * CRC-16 for IP/ICMP headers.
210  *
211  * @param data what to calculate the CRC over
212  * @param bytes number of bytes in data (must be multiple of 2)
213  * @return the CRC 16.
214  */
215 static uint16_t
216 calc_checksum (const uint16_t * data, unsigned int bytes)
217 {
218   uint32_t sum;
219   unsigned int i;
220
221   sum = 0;
222   for (i = 0; i < bytes / 2; i++)
223     sum += data[i];
224   sum = (sum & 0xffff) + (sum >> 16);
225   sum = htons (0xffff - sum);
226   return sum;
227 }
228
229
230 /**
231  * Send an ICMP message to the target.
232  *
233  * @param my_ip source address
234  * @param other target address
235  */
236 static void
237 send_icmp_udp (const struct in_addr *my_ip, const struct in_addr *other)
238 {
239   char packet[sizeof (struct ip_header) * 2 +
240               sizeof (struct icmp_ttl_exceeded_header) +
241               sizeof (struct udp_header)];
242   struct ip_header ip_pkt;
243   struct icmp_ttl_exceeded_header icmp_pkt;
244   struct udp_header udp_pkt;
245   struct sockaddr_in dst;
246   size_t off;
247   int err;
248
249   /* ip header: send to (known) ip address */
250   off = 0;
251   ip_pkt.vers_ihl = 0x45;
252   ip_pkt.tos = 0;
253   ip_pkt.pkt_len = htons (sizeof (packet));
254   ip_pkt.id = htons (256);
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 = htons (calc_checksum ((uint16_t *) & ip_pkt,
262                                           sizeof (struct ip_header)));
263   memcpy (&packet[off], &ip_pkt, sizeof (struct ip_header));
264   off += sizeof (struct ip_header);
265
266   icmp_pkt.type = ICMP_TIME_EXCEEDED;
267   icmp_pkt.code = 0;
268   icmp_pkt.checksum = 0;
269   icmp_pkt.unused = 0;
270   memcpy (&packet[off], &icmp_pkt, sizeof (struct icmp_ttl_exceeded_header));
271   off += sizeof (struct icmp_ttl_exceeded_header);
272
273   /* ip header of the presumably 'lost' udp packet */
274   ip_pkt.vers_ihl = 0x45;
275   ip_pkt.tos = 0;
276   ip_pkt.pkt_len = htons (sizeof (struct ip_header) +
277                           sizeof (struct udp_header));
278   ip_pkt.id = htons (0);
279   ip_pkt.flags_frag_offset = 0;
280   ip_pkt.ttl = 128;
281   ip_pkt.proto = IPPROTO_UDP;
282   ip_pkt.checksum = 0;
283   ip_pkt.src_ip = other->s_addr;
284   ip_pkt.dst_ip = dummy.s_addr;
285   ip_pkt.checksum = htons (calc_checksum ((uint16_t *) & ip_pkt,
286                                           sizeof (struct ip_header)));
287   memcpy (&packet[off], &ip_pkt, sizeof (struct ip_header));
288   off += sizeof (struct ip_header);
289
290   /* build UDP header */
291   udp_pkt.src_port = htons (NAT_TRAV_PORT);
292   udp_pkt.dst_port = htons (NAT_TRAV_PORT);
293   udp_pkt.length = htons (port);
294   udp_pkt.crc = 0;
295   memcpy (&packet[off], &udp_pkt, sizeof (struct udp_header));
296   off += sizeof (struct udp_header);
297
298   /* no go back to calculate ICMP packet checksum */
299   icmp_pkt.checksum = htons (calc_checksum ((uint16_t *) & packet[off],
300                                             sizeof (struct
301                                                     icmp_ttl_exceeded_header) +
302                                             sizeof (struct ip_header) +
303                                             sizeof (struct udp_header)));
304   memcpy (&packet[sizeof (struct ip_header)], &icmp_pkt,
305           sizeof (struct icmp_ttl_exceeded_header));
306
307   memset (&dst, 0, sizeof (dst));
308   dst.sin_family = AF_INET;
309   dst.sin_addr = *other;
310   err = sendto (rawsock,
311                 packet,
312                 sizeof (packet), 0, (struct sockaddr *) &dst, sizeof (dst));
313   if (err < 0)
314   {
315     fprintf (stderr, "sendto failed: %s\n", strerror (errno));
316   }
317   else if (sizeof (packet) != (size_t) err)
318   {
319     fprintf (stderr, "Error: partial send of ICMP message\n");
320   }
321 }
322
323
324 /**
325  * Send an ICMP message to the target.
326  *
327  * @param my_ip source address
328  * @param other target address
329  */
330 static void
331 send_icmp (const struct in_addr *my_ip, const struct in_addr *other)
332 {
333   struct ip_header ip_pkt;
334   struct icmp_ttl_exceeded_header icmp_ttl;
335   struct icmp_echo_header icmp_echo;
336   struct sockaddr_in dst;
337   char packet[sizeof (struct ip_header) * 2 +
338               sizeof (struct icmp_ttl_exceeded_header) +
339               sizeof (struct icmp_echo_header)];
340   size_t off;
341   int err;
342
343   /* ip header: send to (known) ip address */
344   off = 0;
345   ip_pkt.vers_ihl = 0x45;
346   ip_pkt.tos = 0;
347   ip_pkt.pkt_len = htons (sizeof (packet));
348   ip_pkt.id = htons (256);
349   ip_pkt.flags_frag_offset = 0;
350   ip_pkt.ttl = IPDEFTTL;
351   ip_pkt.proto = IPPROTO_ICMP;
352   ip_pkt.checksum = 0;
353   ip_pkt.src_ip = my_ip->s_addr;
354   ip_pkt.dst_ip = other->s_addr;
355   ip_pkt.checksum = htons (calc_checksum ((uint16_t *) & ip_pkt,
356                                           sizeof (struct ip_header)));
357   memcpy (&packet[off], &ip_pkt, sizeof (struct ip_header));
358   off += sizeof (ip_pkt);
359
360   /* icmp reply: time exceeded */
361   icmp_ttl.type = ICMP_TIME_EXCEEDED;
362   icmp_ttl.code = 0;
363   icmp_ttl.checksum = 0;
364   icmp_ttl.unused = 0;
365   memcpy (&packet[off], &icmp_ttl, sizeof (struct icmp_ttl_exceeded_header));
366   off += sizeof (struct icmp_ttl_exceeded_header);
367
368   /* ip header of the presumably 'lost' udp packet */
369   ip_pkt.vers_ihl = 0x45;
370   ip_pkt.tos = 0;
371   ip_pkt.pkt_len =
372       htons (sizeof (struct ip_header) + sizeof (struct icmp_echo_header));
373   ip_pkt.id = htons (256);
374   ip_pkt.flags_frag_offset = 0;
375   ip_pkt.ttl = 1;               /* real TTL would be 1 on a time exceeded packet */
376   ip_pkt.proto = IPPROTO_ICMP;
377   ip_pkt.src_ip = other->s_addr;
378   ip_pkt.dst_ip = dummy.s_addr;
379   ip_pkt.checksum = 0;
380   ip_pkt.checksum = htons (calc_checksum ((uint16_t *) & ip_pkt,
381                                           sizeof (struct ip_header)));
382   memcpy (&packet[off], &ip_pkt, sizeof (struct ip_header));
383   off += sizeof (struct ip_header);
384
385   icmp_echo.type = ICMP_ECHO;
386   icmp_echo.code = 0;
387   icmp_echo.reserved = htonl (port);
388   icmp_echo.checksum = 0;
389   icmp_echo.checksum = htons (calc_checksum ((uint16_t *) & icmp_echo,
390                                              sizeof (struct icmp_echo_header)));
391   memcpy (&packet[off], &icmp_echo, sizeof (struct icmp_echo_header));
392
393   /* no go back to calculate ICMP packet checksum */
394   off = sizeof (struct ip_header);
395   icmp_ttl.checksum = htons (calc_checksum ((uint16_t *) & packet[off],
396                                             sizeof (struct
397                                                     icmp_ttl_exceeded_header) +
398                                             sizeof (struct ip_header) +
399                                             sizeof (struct icmp_echo_header)));
400   memcpy (&packet[off], &icmp_ttl, sizeof (struct icmp_ttl_exceeded_header));
401
402   memset (&dst, 0, sizeof (dst));
403   dst.sin_family = AF_INET;
404   dst.sin_addr = *other;
405
406   err = sendto (rawsock,
407                 packet,
408                 sizeof (packet), 0, (struct sockaddr *) &dst, sizeof (dst));
409
410   if (err < 0)
411   {
412     fprintf (stderr, "sendto failed: %s\n", strerror (errno));
413   }
414   else if (sizeof (packet) != (size_t) err)
415   {
416     fprintf (stderr, "Error: partial send of ICMP message\n");
417   }
418 }
419
420
421 /**
422  * Create an ICMP raw socket.
423  *
424  * @return INVALID_SOCKET on error
425  */
426 static SOCKET
427 make_raw_socket ()
428 {
429   DWORD bOptVal = TRUE;
430   int bOptLen = sizeof (bOptVal);
431   SOCKET ret;
432
433   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
434   if (INVALID_SOCKET == ret)
435   {
436     fprintf (stderr, "Error opening RAW socket: %s\n", strerror (errno));
437     return INVALID_SOCKET;
438   }
439   if (0 !=
440       setsockopt (ret, SOL_SOCKET, SO_BROADCAST, (char *) &bOptVal, bOptLen))
441   {
442     fprintf (stderr,
443              "Error setting SO_BROADCAST to ON: %s\n", strerror (errno));
444     closesocket (rawsock);
445     return INVALID_SOCKET;
446   }
447
448   if (0 != setsockopt (ret, IPPROTO_IP, IP_HDRINCL, (char *) &bOptVal, bOptLen))
449   {
450     fprintf (stderr, "Error setting IP_HDRINCL to ON: %s\n", strerror (errno));
451     closesocket (rawsock);
452     return INVALID_SOCKET;
453   }
454   return ret;
455 }
456
457
458 int
459 main (int argc, char *const *argv)
460 {
461   struct in_addr external;
462   struct in_addr target;
463   WSADATA wsaData;
464
465   unsigned int p;
466
467   if (argc != 4)
468   {
469     fprintf (stderr,
470              "This program must be started with our IP, the targets external IP, and our port as arguments.\n");
471     return 1;
472   }
473   if ((1 != inet_pton (AF_INET, argv[1], &external)) ||
474       (1 != inet_pton (AF_INET, argv[2], &target)))
475   {
476     fprintf (stderr, "Error parsing IPv4 address: %s\n", strerror (errno));
477     return 1;
478   }
479   if ((1 != sscanf (argv[3], "%u", &p)) || (0 == p) || (0xFFFF < p))
480   {
481     fprintf (stderr, "Error parsing port value `%s'\n", argv[3]);
482     return 1;
483   }
484   port = (uint16_t) p;
485
486   if (0 != WSAStartup (MAKEWORD (2, 1), &wsaData))
487   {
488     fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
489     return 2;
490   }
491   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy))
492   {
493     fprintf (stderr, "Internal error converting dummy IP to binary.\n");
494     return 2;
495   }
496   if (-1 == (rawsock = make_raw_socket ()))
497     return 3;
498   send_icmp (&external, &target);
499   send_icmp_udp (&external, &target);
500   closesocket (rawsock);
501   WSACleanup ();
502   return 0;
503 }
504
505 /* end of gnunet-helper-nat-client-windows.c */