(no commit message)
[oweals/gnunet.git] / src / transport / gnunet-nat-server-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-server-windows.c
23  * @brief Windows tool to help bypass NATs using ICMP method
24  *        This code will work under W32 only
25  * @author Christian Grothoff
26  *
27  * This program will send ONE ICMP message every 500 ms RAW sockets
28  * to a DUMMY IP address and also listens for ICMP replies.  Since
29  * it uses RAW sockets, it must be run as an administrative user.
30  * In order to keep the security risk of the resulting binary
31  * minimal, the program ONLY opens the two RAW sockets with administrative
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  * - Nathan Evans
41  * - Christian Grothoff
42  */
43 #define _GNU_SOURCE
44
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  * Should we print some debug output?
60  */
61 #define VERBOSE 0
62
63 /**
64  * Must match IP given in the client.
65  */
66 #define DUMMY_IP "192.0.2.86"
67
68 /**
69  * Default Port
70  */
71 #define NAT_TRAV_PORT 22225
72
73 /**
74  * TTL to use for our outgoing messages.
75  */
76 #define IPDEFTTL 64
77
78 #define ICMP_ECHO 8
79
80 #define ICMP_TIME_EXCEEDED 11
81
82 /**
83  * How often do we send our ICMP messages to receive replies?
84  */
85 #define ICMP_SEND_FREQUENCY_MS 500
86
87 /**
88  * IPv4 header.
89  */
90 struct ip_header
91 {
92
93   /**
94    * Version (4 bits) + Internet header length (4 bits)
95    */
96   uint8_t vers_ihl;
97
98   /**
99    * Type of service
100    */
101   uint8_t tos;
102
103   /**
104    * Total length
105    */
106   uint16_t pkt_len;
107
108   /**
109    * Identification
110    */
111   uint16_t id;
112
113   /**
114    * Flags (3 bits) + Fragment offset (13 bits)
115    */
116   uint16_t flags_frag_offset;
117
118   /**
119    * Time to live
120    */
121   uint8_t  ttl;
122
123   /**
124    * Protocol
125    */
126   uint8_t  proto;
127
128   /**
129    * Header checksum
130    */
131   uint16_t checksum;
132
133   /**
134    * Source address
135    */
136   uint32_t  src_ip;
137
138   /**
139    * Destination address
140    */
141   uint32_t  dst_ip;
142 };
143
144 /**
145  * Format of ICMP packet.
146  */
147 struct icmp_ttl_exceeded_header
148 {
149   uint8_t type;
150
151   uint8_t code;
152
153   uint16_t checksum;
154
155   uint32_t unused;
156
157   /* followed by original payload */
158 };
159
160 struct icmp_echo_header
161 {
162   uint8_t type;
163
164   uint8_t code;
165
166   uint16_t checksum;
167
168   uint32_t reserved;
169 };
170
171 /**
172  * Beginning of UDP packet.
173  */
174 struct udp_header
175 {
176   uint16_t src_port;
177
178   uint16_t dst_port;
179
180   uint16_t length;
181
182   uint16_t crc;
183 };
184
185 /**
186  * Socket we use to receive "fake" ICMP replies.
187  */
188 static SOCKET icmpsock;
189
190 /**
191  * Socket we use to send our ICMP requests.
192  */
193 static SOCKET rawsock;
194
195 /**
196  * Socket we use to send our UDP requests.
197  */
198 static SOCKET udpsock;
199
200 /**
201  * Target "dummy" address.
202  */
203 static struct in_addr dummy;
204
205
206 /**
207  * CRC-16 for IP/ICMP headers.
208  *
209  * @param data what to calculate the CRC over
210  * @param bytes number of bytes in data (must be multiple of 2)
211  * @return the CRC 16.
212  */
213 static uint16_t
214 calc_checksum(const uint16_t *data,
215               unsigned int bytes)
216 {
217   uint32_t sum;
218   unsigned int i;
219
220   sum = 0;
221   for (i=0;i<bytes/2;i++)
222     sum += data[i];
223   sum = (sum & 0xffff) + (sum >> 16);
224   sum = htons(0xffff - sum);
225   return sum;
226 }
227
228
229 /**
230  * Convert IPv4 address from text to binary form.
231  *
232  * @param af address family
233  * @param cp the address to print
234  * @param buf where to write the address result
235  * @return 1 on success
236  */
237 static int
238 inet_pton (int af,
239            const char *cp,
240            struct in_addr *buf)
241 {
242   buf->s_addr = inet_addr(cp);
243   if (buf->s_addr == INADDR_NONE)
244     {
245       fprintf(stderr,
246               "Error %d handling address %s",
247               WSAGetLastError(),
248               cp);
249       return 0;
250     }
251   return 1;
252 }
253
254
255 /**
256  * Send an ICMP message to the dummy IP.
257  *
258  * @param my_ip source address (our ip address)
259  */
260 static void
261 send_icmp_echo (const struct in_addr *my_ip)
262 {
263   char packet[sizeof (struct ip_header) + sizeof (struct icmp_echo_header)];
264   struct icmp_echo_header icmp_echo;
265   struct ip_header ip_pkt;
266   struct sockaddr_in dst;
267   size_t off;
268   int err;
269
270   off = 0;
271   ip_pkt.vers_ihl = 0x45;
272   ip_pkt.tos = 0;
273   ip_pkt.pkt_len = htons (sizeof (packet));
274   ip_pkt.id = htons (256);
275   ip_pkt.flags_frag_offset = 0;
276   ip_pkt.ttl = IPDEFTTL;
277   ip_pkt.proto = IPPROTO_ICMP;
278   ip_pkt.checksum = 0;
279   ip_pkt.src_ip = my_ip->s_addr;
280   ip_pkt.dst_ip = dummy.s_addr;
281   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt,
282                                         sizeof (struct ip_header)));
283   memcpy (&packet[off],
284           &ip_pkt,
285           sizeof (struct ip_header));
286   off += sizeof (struct ip_header);
287
288   icmp_echo.type = ICMP_ECHO;
289   icmp_echo.code = 0;
290   icmp_echo.reserved = 0;
291   icmp_echo.checksum = 0;
292   icmp_echo.checksum = htons(calc_checksum((uint16_t*) &icmp_echo,
293                                            sizeof (struct icmp_echo_header)));
294   memcpy (&packet[off],
295           &icmp_echo,
296           sizeof (struct icmp_echo_header));
297   off += sizeof (struct icmp_echo_header);
298
299   memset (&dst, 0, sizeof (dst));
300   dst.sin_family = AF_INET;
301   dst.sin_addr = dummy;
302   err = sendto(rawsock,
303                packet, off, 0,
304                (struct sockaddr*)&dst,
305                sizeof(dst));
306   if (err < 0)
307     {
308 #if VERBOSE
309       fprintf(stderr,
310               "sendto failed: %s\n", strerror(errno));
311 #endif
312     }
313   else if (err != off)
314     {
315       fprintf(stderr,
316               "Error: partial send of ICMP message\n");
317     }
318 }
319
320
321 /**
322  * Send a UDP message to the dummy IP.
323  */
324 static void
325 send_udp ()
326 {
327   struct sockaddr_in dst;
328   ssize_t err;
329
330   memset (&dst, 0, sizeof (dst));
331   dst.sin_family = AF_INET;
332   dst.sin_addr = dummy;
333   dst.sin_port = htons (NAT_TRAV_PORT);
334   err = sendto(udpsock,
335                NULL, 0, 0,
336                (struct sockaddr*)&dst,
337                sizeof(dst));
338   if (err < 0)
339     {
340 #if VERBOSE
341       fprintf(stderr,
342               "sendto failed: %s\n", strerror(errno));
343 #endif
344     }
345   else if (0 != err)
346     {
347       fprintf(stderr,
348               "Error: partial send of ICMP message\n");
349     }
350 }
351
352
353 /**
354  * We've received an ICMP response.  Process it.
355  */
356 static void
357 process_icmp_response ()
358 {
359   char buf[65536];
360   ssize_t have;
361   struct in_addr source_ip;
362   struct ip_header ip_pkt;
363   struct icmp_ttl_exceeded_header icmp_ttl;
364   struct icmp_echo_header icmp_echo;
365   struct udp_header udp_pkt;
366   size_t off;
367   uint16_t port;
368   DWORD ssize;
369
370   have = read (icmpsock, buf, sizeof (buf));
371   if (have == -1)
372     {
373       fprintf (stderr,
374                "Error reading raw socket: %s\n",
375                strerror (errno));
376       return;
377     }
378 #if VERBOSE
379   fprintf (stderr,
380            "Received message of %u bytes\n",
381            (unsigned int) have);
382 #endif
383   if (have < (ssize_t) (sizeof (struct ip_header) + sizeof (struct icmp_ttl_exceeded_header) + sizeof (struct ip_header)))
384     {
385       /* malformed */
386       return;
387     }
388   off = 0;
389   memcpy (&ip_pkt,
390           &buf[off],
391           sizeof (struct ip_header));
392   off += sizeof (struct ip_header);
393   memcpy(&source_ip,
394          &ip_pkt.src_ip,
395          sizeof (source_ip));
396   memcpy (&icmp_ttl,
397           &buf[off],
398           sizeof (struct icmp_ttl_exceeded_header));
399   off += sizeof (struct icmp_ttl_exceeded_header);
400   if ( (ICMP_TIME_EXCEEDED != icmp_ttl.type) ||
401        (0 != icmp_ttl.code) )
402     {
403       /* different type than what we want */
404       return;
405     }
406   /* skip 2nd IP header */
407   memcpy (&ip_pkt,
408           &buf[off],
409           sizeof (struct ip_header));
410   off += sizeof (struct ip_header);
411
412   switch (ip_pkt.proto)
413     {
414     case IPPROTO_ICMP:
415       if (have != (sizeof (struct ip_header) * 2 +
416                    sizeof (struct icmp_ttl_exceeded_header) +
417                    sizeof (struct icmp_echo_header)) )
418         {
419           /* malformed */
420           return;
421         }
422       /* grab ICMP ECHO content */
423       memcpy (&icmp_echo,
424               &buf[off],
425               sizeof (struct icmp_echo_header));
426       port = (uint16_t)  ntohl (icmp_echo.reserved);
427       break;
428     case IPPROTO_UDP:
429       if (have != (sizeof (struct ip_header) * 2 +
430                    sizeof (struct icmp_ttl_exceeded_header) +
431                    sizeof (struct udp_header)) )
432         {
433           /* malformed */
434           return;
435         }
436       /* grab UDP content */
437       memcpy (&udp_pkt,
438               &buf[off],
439               sizeof (struct udp_header));
440       port = ntohs (udp_pkt.length);
441       break;
442     default:
443       /* different type than what we want */
444       return;
445     }
446
447   ssize = sizeof(buf);
448   WSAAddressToString((LPSOCKADDR)&source_ip,
449                      sizeof(source_ip),
450                      NULL,
451                      buf,
452                      &ssize);
453   if (port == 0)
454     fprintf (stdout,
455              "%s\n",
456              buf);
457   else
458     fprintf (stdout,
459              "%s:%u\n",
460              buf,
461              (unsigned int) port);
462   fflush (stdout);
463 }
464
465
466 /**
467  * Create an ICMP raw socket for reading.
468  *
469  * @return INVALID_SOCKET on error
470  */
471 static SOCKET
472 make_icmp_socket ()
473 {
474   SOCKET ret;
475
476   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
477   if (INVALID_SOCKET == ret)
478     {
479       fprintf (stderr,
480                "Error opening RAW socket: %s\n",
481                strerror (errno));
482       return INVALID_SOCKET;
483     }
484   return ret;
485 }
486
487
488 /**
489  * Create an ICMP raw socket for writing.
490  *
491  * @return INVALID_SOCKET on error
492  */
493 static SOCKET
494 make_raw_socket ()
495 {
496   DWORD bOptVal = TRUE;
497   int bOptLen = sizeof(bOptVal);
498
499   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
500   if (INVALID_SOCKET == rawsock)
501     {
502       fprintf (stderr,
503                "Error opening RAW socket: %s\n",
504                strerror (errno));
505       return INVALID_SOCKET;
506     }
507
508   if (0 != setsockopt(rawsock,
509                       SOL_SOCKET,
510                       SO_BROADCAST,
511                       (char*)&bOptVal, bOptLen))
512     {
513       fprintf(stderr,
514               "Error setting SO_BROADCAST to ON: %s\n",
515               strerror (errno));
516       closesocket(rawsock);
517       return INVALID_SOCKET;
518     }
519   if (0 != setsockopt(rawsock,
520                       IPPROTO_IP,
521                       IP_HDRINCL,
522                       (char*)&bOptVal, bOptLen))
523     {
524       fprintf(stderr,
525               "Error setting IP_HDRINCL to ON: %s\n",
526               strerror (errno));
527       closesocket(rawsock);
528       return INVALID_SOCKET;
529     }
530   return rawsock;
531 }
532
533
534 /**
535  * Create a UDP socket for writing.
536  *
537  * @param my_ip source address (our ip address)
538  * @return INVALID_SOCKET on error
539  */
540 static SOCKET
541 make_udp_socket (const struct in_addr *my_ip)
542 {
543   SOCKET ret;
544   struct sockaddr_in addr;
545
546   ret = socket (AF_INET, SOCK_DGRAM, 0);
547   if (INVALID_SOCKET == ret)
548     {
549       fprintf (stderr,
550                "Error opening UDP socket: %s\n",
551                strerror (errno));
552       return INVALID_SOCKET;
553     }
554   memset (&addr, 0, sizeof (addr));
555   addr.sin_family = AF_INET;
556   addr.sin_addr = *my_ip;
557   addr.sin_port = htons (NAT_TRAV_PORT);
558   if (0 != bind (ret,
559                  (struct sockaddr *)&addr,
560                  sizeof(addr)))
561     {
562       fprintf (stderr,
563                "Error binding UDP socket to port %u: %s\n",
564                NAT_TRAV_PORT,
565                strerror (errno));
566       /* likely problematic, but not certain, try to continue */
567     }
568   return ret;
569 }
570
571
572 int
573 main (int argc,
574       char *const *argv)
575 {
576   struct in_addr external;
577   fd_set rs;
578   struct timeval tv;
579   WSADATA wsaData;
580   unsigned int alt;
581
582   alt = 0;
583   if (2 != argc)
584     {
585       fprintf (stderr,
586                "This program must be started with our (internal NAT) IP as the only argument.\n");
587       return 1;
588     }
589   if (1 != inet_pton (AF_INET, argv[1], &external))
590     {
591       fprintf (stderr,
592                "Error parsing IPv4 address: %s, error %s\n",
593                argv[1], strerror (errno));
594       return 1;
595     }
596   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy))
597     {
598       fprintf (stderr,
599                "Internal error converting dummy IP to binary.\n");
600       return 2;
601     }
602   if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
603     {
604       fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
605       return 2;
606     }
607   if (INVALID_SOCKET == (icmpsock = make_icmp_socket()))
608     {
609       return 3;
610     }
611   if (INVALID_SOCKET == (make_raw_socket()))
612     {
613       closesocket (icmpsock);
614       return 3;
615     }
616   if (INVALID_SOCKET == (udpsock = make_udp_socket(&external)))
617     {
618       closesocket (icmpsock);
619       closesocket (rawsock);
620       return 3;
621     }
622   while (1)
623     {
624       FD_ZERO (&rs);
625       FD_SET (icmpsock, &rs);
626       tv.tv_sec = 0;
627       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000;
628       if (-1 == select (icmpsock + 1, &rs, NULL, NULL, &tv))
629         {
630           if (errno == EINTR)
631             continue;
632           fprintf (stderr,
633                    "select failed: %s\n",
634                    strerror (errno));
635           break;
636         }
637       if (FD_ISSET (icmpsock, &rs))
638         process_icmp_response ();
639       if (0 == (++alt % 2))
640         send_icmp_echo (&external);
641       else
642         send_udp ();
643     }
644   /* select failed (internal error or OS out of resources) */
645   closesocket(icmpsock);
646   closesocket(rawsock);
647   closesocket(udpsock);
648   WSACleanup ();
649   return 4;
650 }
651
652
653 /* end of gnunet-nat-server-windows.c */