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