fixing: assertion failed at transport_api_new.c:1277
[oweals/gnunet.git] / src / transport / gnunet-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/transport/gnunet-nat-client-windows.c
23  * @brief Tool to help bypass NATs using ICMP method; must run as
24  *        root (SUID will do) or administrator on W32
25  *        This code will work under GNU/Linux or 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,
197            const char *cp,
198            struct in_addr *buf)
199 {
200   buf->s_addr = inet_addr(cp);
201   if (buf->s_addr == INADDR_NONE)
202     {
203       fprintf(stderr,
204               "Error %d handling address %s",
205               WSAGetLastError(),
206               cp);
207       return 0;
208     }
209   return 1;
210 }
211
212
213 /**
214  * CRC-16 for IP/ICMP headers.
215  *
216  * @param data what to calculate the CRC over
217  * @param bytes number of bytes in data (must be multiple of 2)
218  * @return the CRC 16.
219  */
220 static uint16_t
221 calc_checksum(const uint16_t *data,
222               unsigned int bytes)
223 {
224   uint32_t sum;
225   unsigned int i;
226
227   sum = 0;
228   for (i=0;i<bytes/2;i++)
229     sum += data[i];
230   sum = (sum & 0xffff) + (sum >> 16);
231   sum = htons(0xffff - sum);
232   return sum;
233 }
234
235
236 /**
237  * Send an ICMP message to the target.
238  *
239  * @param my_ip source address
240  * @param other target address
241  */
242 static void
243 send_icmp_udp (const struct in_addr *my_ip,
244                const struct in_addr *other)
245 {
246   char packet[sizeof(struct ip_header) * 2 +
247               sizeof(struct icmp_ttl_exceeded_header) +
248               sizeof(struct udp_header)];
249   struct ip_header ip_pkt;
250   struct icmp_ttl_exceeded_header icmp_pkt;
251   struct udp_header udp_pkt;
252   struct sockaddr_in dst;
253   size_t off;
254   int err;
255
256   /* ip header: send to (known) ip address */
257   off = 0;
258   ip_pkt.vers_ihl = 0x45;
259   ip_pkt.tos = 0;
260   ip_pkt.pkt_len = htons(sizeof (packet));
261   ip_pkt.id = htons(256);
262   ip_pkt.flags_frag_offset = 0;
263   ip_pkt.ttl = 128;
264   ip_pkt.proto = IPPROTO_ICMP;
265   ip_pkt.checksum = 0;
266   ip_pkt.src_ip = my_ip->s_addr;
267   ip_pkt.dst_ip = other->s_addr;
268   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt,
269                                         sizeof (struct ip_header)));
270   memcpy(&packet[off],
271          &ip_pkt,
272          sizeof(struct ip_header));
273   off += sizeof(struct ip_header);
274
275   icmp_pkt.type = ICMP_TIME_EXCEEDED;
276   icmp_pkt.code = 0;
277   icmp_pkt.checksum = 0;
278   icmp_pkt.unused = 0;
279   memcpy(&packet[off],
280          &icmp_pkt,
281          sizeof(struct icmp_ttl_exceeded_header));
282   off += sizeof(struct icmp_ttl_exceeded_header);
283
284   /* ip header of the presumably 'lost' udp packet */
285   ip_pkt.vers_ihl = 0x45;
286   ip_pkt.tos = 0;
287   ip_pkt.pkt_len = htons(sizeof (struct ip_header) +
288                          sizeof (struct udp_header));
289   ip_pkt.id = htons(0);
290   ip_pkt.flags_frag_offset = 0;
291   ip_pkt.ttl = 128;
292   ip_pkt.proto = IPPROTO_UDP;
293   ip_pkt.checksum = 0;
294   ip_pkt.src_ip = other->s_addr;
295   ip_pkt.dst_ip = dummy.s_addr;
296   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt,
297                                         sizeof (struct ip_header)));
298   memcpy(&packet[off],
299          &ip_pkt,
300          sizeof(struct ip_header));
301   off += sizeof(struct ip_header);
302
303   /* build UDP header */
304   udp_pkt.src_port = htons(NAT_TRAV_PORT);
305   udp_pkt.dst_port = htons(NAT_TRAV_PORT);
306   udp_pkt.length = htons (port);
307   udp_pkt.crc = 0;
308   memcpy(&packet[off],
309          &udp_pkt,
310          sizeof(struct udp_header));
311   off += sizeof(struct udp_header);
312
313   /* no go back to calculate ICMP packet checksum */
314   icmp_pkt.checksum = htons(calc_checksum((uint16_t*)&packet[off],
315                                           sizeof (struct icmp_ttl_exceeded_header) +
316                                           sizeof (struct ip_header) +
317                                           sizeof (struct udp_header)));
318   memcpy (&packet[sizeof (struct ip_header)],
319           &icmp_pkt,
320           sizeof (struct icmp_ttl_exceeded_header));
321
322   memset (&dst, 0, sizeof (dst));
323   dst.sin_family = AF_INET;
324   dst.sin_addr = *other;
325   err = sendto(rawsock,
326                packet,
327                sizeof (packet), 0,
328                (struct sockaddr*)&dst,
329                sizeof(dst));
330   if (err < 0)
331     {
332       fprintf(stderr,
333               "sendto failed: %s\n", strerror(errno));
334     }
335   else if (sizeof (packet) != (size_t) err)
336     {
337       fprintf(stderr,
338               "Error: partial send of ICMP message\n");
339     }
340 }
341
342
343 /**
344  * Send an ICMP message to the target.
345  *
346  * @param my_ip source address
347  * @param other target address
348  */
349 static void
350 send_icmp (const struct in_addr *my_ip,
351            const struct in_addr *other)
352 {
353   struct ip_header ip_pkt;
354   struct icmp_ttl_exceeded_header icmp_ttl;
355   struct icmp_echo_header icmp_echo;
356   struct sockaddr_in dst;
357   char packet[sizeof (struct ip_header) * 2 +
358               sizeof (struct icmp_ttl_exceeded_header) +
359               sizeof(struct icmp_echo_header)];
360   size_t off;
361   int err;
362
363   /* ip header: send to (known) ip address */
364   off = 0;
365   ip_pkt.vers_ihl = 0x45;
366   ip_pkt.tos = 0;
367   ip_pkt.pkt_len = htons (sizeof (packet));
368   ip_pkt.id = htons(256);
369   ip_pkt.flags_frag_offset = 0;
370   ip_pkt.ttl = IPDEFTTL;
371   ip_pkt.proto = IPPROTO_ICMP;
372   ip_pkt.checksum = 0;
373   ip_pkt.src_ip = my_ip->s_addr;
374   ip_pkt.dst_ip = other->s_addr;
375   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt,
376                                         sizeof (struct ip_header)));
377   memcpy (&packet[off],
378           &ip_pkt,
379           sizeof (struct ip_header));
380   off += sizeof (ip_pkt);
381
382   /* icmp reply: time exceeded */
383   icmp_ttl.type = ICMP_TIME_EXCEEDED;
384   icmp_ttl.code = 0;
385   icmp_ttl.checksum = 0;
386   icmp_ttl.unused = 0; 
387   memcpy (&packet[off],
388           &icmp_ttl,
389           sizeof (struct icmp_ttl_exceeded_header));
390   off += sizeof (struct icmp_ttl_exceeded_header);
391
392   /* ip header of the presumably 'lost' udp packet */
393   ip_pkt.vers_ihl = 0x45;
394   ip_pkt.tos = 0;
395   ip_pkt.pkt_len = htons(sizeof (struct ip_header) + sizeof (struct icmp_echo_header));
396   ip_pkt.id = htons (256);
397   ip_pkt.flags_frag_offset = 0;
398   ip_pkt.ttl = 1; /* real TTL would be 1 on a time exceeded packet */
399   ip_pkt.proto = IPPROTO_ICMP;
400   ip_pkt.src_ip = other->s_addr;
401   ip_pkt.dst_ip = dummy.s_addr;
402   ip_pkt.checksum = 0;
403   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt,
404                                         sizeof (struct ip_header)));
405   memcpy (&packet[off],
406           &ip_pkt,
407           sizeof (struct ip_header));
408   off += sizeof (struct ip_header);
409
410   icmp_echo.type = ICMP_ECHO;
411   icmp_echo.code = 0;
412   icmp_echo.reserved = htonl(port);
413   icmp_echo.checksum = 0;
414   icmp_echo.checksum = htons(calc_checksum((uint16_t*) &icmp_echo,
415                                            sizeof (struct icmp_echo_header)));
416   memcpy (&packet[off],
417           &icmp_echo,
418           sizeof(struct icmp_echo_header));
419
420   /* no go back to calculate ICMP packet checksum */
421   off = sizeof (struct ip_header);
422   icmp_ttl.checksum = htons(calc_checksum((uint16_t*) &packet[off],
423                                           sizeof (struct icmp_ttl_exceeded_header) +
424                                           sizeof (struct ip_header) +
425                                           sizeof (struct icmp_echo_header)));
426   memcpy (&packet[off],
427           &icmp_ttl,
428           sizeof (struct icmp_ttl_exceeded_header));
429
430   memset (&dst, 0, sizeof (dst));
431   dst.sin_family = AF_INET;
432   dst.sin_addr = *other;
433
434   err = sendto(rawsock,
435                packet,
436                sizeof (packet), 0,
437                (struct sockaddr*)&dst,
438                sizeof(dst));
439
440   if (err < 0)
441     {
442       fprintf(stderr,
443               "sendto failed: %s\n", strerror(errno));
444     }
445   else if (sizeof (packet) != (size_t) err)
446     {
447       fprintf(stderr,
448               "Error: partial send of ICMP message\n");
449     }
450 }
451
452
453 /**
454  * Create an ICMP raw socket.
455  *
456  * @return INVALID_SOCKET on error
457  */
458 static SOCKET
459 make_raw_socket ()
460 {
461   DWORD bOptVal = TRUE;
462   int bOptLen = sizeof(bOptVal);
463   SOCKET ret;
464
465   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
466   if (INVALID_SOCKET == ret)
467     {
468       fprintf (stderr,
469                "Error opening RAW socket: %s\n",
470                strerror (errno));
471       return INVALID_SOCKET;
472     }
473   if (0 != setsockopt(ret, SOL_SOCKET, SO_BROADCAST, (char*)&bOptVal, bOptLen))
474     {
475       fprintf(stderr,
476               "Error setting SO_BROADCAST to ON: %s\n",
477               strerror (errno));
478       closesocket(rawsock);
479       return INVALID_SOCKET;
480     }
481
482   if (0 != setsockopt(ret, IPPROTO_IP, IP_HDRINCL, (char*)&bOptVal, bOptLen))
483     {
484       fprintf(stderr,
485               "Error setting IP_HDRINCL to ON: %s\n",
486               strerror (errno));
487       closesocket(rawsock);
488       return INVALID_SOCKET;
489     }
490   return ret;
491 }
492
493
494 int
495 main (int argc, char *const *argv)
496 {
497   struct in_addr external;
498   struct in_addr target;
499   WSADATA wsaData;
500
501   unsigned int p;
502
503   if (argc != 4)
504     {
505       fprintf (stderr,
506                "This program must be started with our IP, the targets external IP, and our port as arguments.\n");
507       return 1;
508     }
509   if ( (1 != inet_pton (AF_INET, argv[1], &external)) ||
510        (1 != inet_pton (AF_INET, argv[2], &target)) )
511     {
512       fprintf (stderr,
513                "Error parsing IPv4 address: %s\n",
514                strerror (errno));
515       return 1;
516     }
517   if ( (1 != sscanf (argv[3], "%u", &p) ) ||
518        (0 == p) ||
519        (0xFFFF < p) )
520     {
521       fprintf (stderr,
522                "Error parsing port value `%s'\n",
523                argv[3]);
524       return 1;
525     }
526   port = (uint16_t) p;
527
528   if (0 != WSAStartup (MAKEWORD (2, 1), &wsaData))
529     {
530       fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
531       return 2;
532     }
533   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy))
534     {
535       fprintf (stderr,
536                "Internal error converting dummy IP to binary.\n");
537       return 2;
538     }
539   if (-1 == (rawsock = make_raw_socket()))
540     return 3;
541   send_icmp (&external,
542              &target);
543   send_icmp_udp (&external,
544                  &target);
545   closesocket (rawsock);
546   WSACleanup ();
547   return 0;
548 }
549
550 /* end of gnunet-nat-client-windows.c */