b05690e88870f8a258e1811dc6b2bfd9a20c886a
[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  */
42 #define _GNU_SOURCE
43
44
45 #include <winsock2.h>
46 #include <ws2tcpip.h>
47 #include <sys/time.h>
48 #include <sys/types.h>
49 #include <unistd.h>
50 #include <stdio.h>
51 #include <string.h>
52 #include <errno.h>
53 #include <stdlib.h>
54 #include <stdint.h>
55 #include <time.h>
56
57 /**
58  * Should we print some debug output?
59  */
60 #define VERBOSE 0
61
62
63 typedef unsigned int uid_t;
64 typedef SOCKET Socket;
65 typedef unsigned short ushort;
66 #define IPDEFTTL 64
67 #define ICMP_ECHO 8
68 #define ICMP_TIME_EXCEEDED      11      /* Time Exceeded
69
70 /**
71  * Must match IP given in the client.
72  */
73 #define DUMMY_IP "192.0.2.86"
74
75 /**
76  * How often do we send our ICMP messages to receive replies?
77  */
78 #define ICMP_SEND_FREQUENCY_MS 500
79
80 /**
81  * IPv4 header.
82  */
83 struct ip_packet 
84 {
85
86   /**
87    * Version (4 bits) + Internet header length (4 bits) 
88    */
89   u_char vers_ihl; 
90
91   /**
92    * Type of service
93    */
94   u_char tos;  
95
96   /**
97    * Total length
98    */
99   u_short pkt_len;  
100
101   /**
102    * Identification
103    */
104   u_short id;    
105
106   /**
107    * Flags (3 bits) + Fragment offset (13 bits)
108    */
109   u_short flags_frag_offset; 
110
111   /**
112    * Time to live
113    */
114   u_char  ttl;   
115
116   /**
117    * Protocol       
118    */
119   u_char  proto; 
120
121   /**
122    * Header checksum
123    */
124   u_short checksum; 
125
126   /**
127    * Source address
128    */
129   u_long  src_ip;  
130
131   /**
132    * Destination address 
133    */
134   u_long  dst_ip;  
135 };
136
137 /**
138  * Format of ICMP packet.
139  */
140 struct icmp_packet 
141 {
142   uint8_t type;
143   uint8_t code;
144   uint16_t checksum;
145   uint32_t reserved;
146 };
147
148 /**
149  * Beginning of UDP packet.
150  */
151 struct udp_packet
152 {
153   uint16_t src_port;
154
155   uint16_t dst_port;
156
157   uint32_t length;
158 };
159
160 static Socket icmpsock;
161
162 static Socket rawsock;
163
164 static struct in_addr dummy;
165
166 /**
167  * CRC-16 for IP/ICMP headers.
168  */
169 static uint16_t 
170 calc_checksum(const uint16_t *data, 
171               unsigned int bytes)
172 {
173   uint32_t sum;
174   unsigned int i;
175
176   sum = 0;
177   for (i=0;i<bytes/2;i++) 
178     sum += data[i];        
179   sum = (sum & 0xffff) + (sum >> 16);
180   sum = htons(0xffff - sum);
181   return sum;
182 }
183
184 /**
185  * Convert IPv4 address from text to binary form.
186  *
187  * @param af address family
188  * @param cp the address to print
189  * @param buf where to write the address result
190  */
191 static int 
192 inet_pton (int af, 
193            const char *cp, 
194            struct in_addr *buf)
195 {
196   buf->s_addr = inet_addr(cp);
197   if (buf->s_addr == INADDR_NONE)
198     {
199       fprintf(stderr, 
200               "Error %d handling address %s", 
201               WSAGetLastError(), 
202               cp);
203       return 0;
204     }
205   return 1;
206 }
207
208
209 /**
210  * Send an ICMP message to the dummy IP.
211  *
212  * @param my_ip source address (our ip address)
213  */
214 static void
215 send_icmp_echo (const struct in_addr *my_ip)
216 {
217   struct icmp_packet icmp_echo;
218   struct sockaddr_in dst;
219   size_t off;
220   int err;
221   struct ip_packet ip_pkt;
222   struct icmp_packet icmp_pkt;
223   char packet[sizeof (ip_pkt) + sizeof (icmp_pkt)];
224
225   off = 0;
226   memset(&ip_pkt, 0, sizeof(ip_pkt));
227   ip_pkt.vers_ihl = 0x45;
228   ip_pkt.tos = 0;
229   ip_pkt.pkt_len = sizeof (packet);
230   ip_pkt.id = htons (256);
231   ip_pkt.flags_frag_offset = 0;
232   ip_pkt.ttl = IPDEFTTL;
233   ip_pkt.proto = IPPROTO_ICMP;
234   ip_pkt.checksum = 0;
235   ip_pkt.src_ip = my_ip->s_addr;
236   ip_pkt.dst_ip = dummy.s_addr;
237   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
238   memcpy (packet, &ip_pkt, sizeof (ip_pkt));
239   off += sizeof (ip_pkt);
240
241   icmp_echo.type = ICMP_ECHO;
242   icmp_echo.code = 0;
243   icmp_echo.reserved = 0;
244   icmp_echo.checksum = 0;
245   icmp_echo.checksum = htons(calc_checksum((uint16_t*) &icmp_echo, 
246                                            sizeof (struct icmp_packet)));
247   memcpy (&packet[off], &icmp_echo, sizeof (icmp_echo));
248   off += sizeof (icmp_echo);
249  
250   memset (&dst, 0, sizeof (dst));
251   dst.sin_family = AF_INET;
252   dst.sin_addr = dummy;
253   err = sendto(rawsock, 
254                packet, off, 0,
255                (struct sockaddr*)&dst,
256                sizeof(dst));
257   if (err < 0) 
258     {
259 #if VERBOSE
260       fprintf(stderr,
261               "sendto failed: %s\n", strerror(errno));
262 #endif
263     }
264   else if (err != off) 
265     {
266       fprintf(stderr,
267               "Error: partial send of ICMP message\n");
268     }
269 }
270
271
272 static void
273 process_icmp_response ()
274 {
275   char buf[65536];
276   ssize_t have;
277   struct in_addr sip;
278   struct ip_packet ip_pkt;
279   struct icmp_packet icmp_pkt;
280   struct udp_packet udp_pkt;
281   size_t off;
282   int have_port;
283   int have_udp;
284   uint32_t port;
285
286   have = read (icmpsock, buf, sizeof (buf));
287   if (have == -1)
288     {
289       fprintf (stderr,
290                "Error reading raw socket: %s\n",
291                strerror (errno));
292       return; 
293     }
294   have_port = 0;
295 #if VERBOSE
296   fprintf (stderr,
297            "Received message of %u bytes\n",
298            (unsigned int) have);
299 #endif
300   if (have == sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2 + sizeof(uint32_t))
301     {
302       have_port = 1;
303     }
304   else if (have != sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2)
305     {
306 #if VERBOSE
307       fprintf (stderr,
308                "Received ICMP message of unexpected size: %u bytes\n",
309                (unsigned int) have);
310 #endif
311       return;
312     }
313   off = 0;
314   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
315   off += sizeof (ip_pkt);
316   memcpy (&icmp_pkt, &buf[off], sizeof (icmp_pkt));
317   off += sizeof (icmp_pkt);
318   if ( ((ip_pkt.proto != IPPROTO_ICMP) && (ip_pkt.proto != IPPROTO_UDP)) ||
319        (icmp_pkt.type != ICMP_TIME_EXCEEDED) || 
320        (icmp_pkt.code != 0) )
321     {
322       /* maybe we got an actual reply back... */
323       return;    
324     }
325   memcpy(&sip, 
326          &ip_pkt.src_ip, 
327          sizeof (sip));
328   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
329   off += sizeof (ip_pkt);
330   have_udp = (ip_pkt.proto == IPPROTO_UDP);
331
332   if (have_port)
333     {
334       memcpy(&port, 
335              &buf[sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2], 
336              sizeof(uint32_t));
337       port = ntohs(port);
338       DWORD ssize = sizeof(buf);
339       WSAAddressToString((LPSOCKADDR)&sip, 
340                          sizeof(sip),
341                          NULL, 
342                          buf, 
343                          &ssize);
344       fprintf (stdout, 
345                "%s:%d\n",
346                buf, 
347                port);
348     }
349   else if (have_udp)
350     {
351       memcpy(&udp_pkt,
352              &buf[off],
353              sizeof(udp_pkt));
354       DWORD ssize = sizeof(buf);
355       WSAAddressToString((LPSOCKADDR)&sip, 
356                          sizeof(sip),
357                          NULL,
358                          buf, 
359                          &ssize);
360       fprintf (stdout, 
361                "%s:%d\n", 
362                buf, 
363                ntohs((int)udp_pkt.length));
364     }
365   else
366     {
367       DWORD ssize = sizeof(buf);
368       WSAAddressToString((LPSOCKADDR)&sip,
369                          sizeof(sip),
370                          NULL,
371                          buf,
372                          &ssize);
373       fprintf (stdout, 
374                "%s\n",
375                buf);
376     }
377   fflush (stdout);
378 }
379
380
381 static Socket
382 make_icmp_socket ()
383 {
384   Socket ret;
385
386   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
387   if (INVALID_SOCKET == ret)
388     {
389       fprintf (stderr,
390                "Error opening RAW socket: %s\n",
391                strerror (errno));
392       return -1;
393     }  
394   return ret;
395 }
396
397
398 static Socket
399 make_raw_socket ()
400 {
401   DWORD bOptVal = TRUE;
402   int bOptLen = sizeof(bOptVal);
403
404   rawsock = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
405   if (INVALID_SOCKET == rawsock)
406     {
407       fprintf (stderr,
408                "Error opening RAW socket: %s\n",
409                strerror (errno));
410       return INVALID_SOCKET;
411     }
412
413   if (setsockopt(rawsock, 
414                  SOL_SOCKET, 
415                  SO_BROADCAST, 
416                  (char*)&bOptVal, bOptLen) != 0)
417     {
418       fprintf(stderr, 
419               "Error setting SO_BROADCAST to ON: %s\n",
420               strerror (errno));
421       closesocket(rawsock);
422       return INVALID_SOCKET;
423     }
424   if (setsockopt(rawsock, 
425                  IPPROTO_IP, 
426                  IP_HDRINCL, 
427                  (char*)&bOptVal, bOptLen) != 0)
428     {
429       fprintf(stderr, 
430               "Error setting IP_HDRINCL to ON: %s\n",
431               strerror (errno));
432       closesocket(rawsock);
433       return INVALID_SOCKET;
434     }
435   return rawsock;
436 }
437
438
439 int
440 main (int argc, 
441       char *const *argv)
442 {
443   struct in_addr external;
444   fd_set rs;
445   struct timeval tv;
446   WSADATA wsaData;
447
448   if (argc != 2)
449     {
450       fprintf (stderr,
451                "This program must be started with our (internal NAT) IP as the only argument.\n");
452       return 1;
453     }
454   if (1 != inet_pton (AF_INET, argv[1], &external))
455     {
456       fprintf (stderr,
457                "Error parsing IPv4 address: %s, error %s\n",
458                argv[1], strerror (errno));
459       return 1;
460     }
461   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) 
462     {
463       fprintf (stderr,
464                "Internal error converting dummy IP to binary.\n");
465       return 2;
466     }
467   if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
468     {
469       fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
470       return 2;
471     }
472   if (-1 == (icmpsock = make_icmp_socket()))
473     {
474       return 3; 
475     }
476   if (-1 == (make_raw_socket()))
477     {
478       closesocket (icmpsock);
479       return 3; 
480     }
481   while (1)
482     {
483       FD_ZERO (&rs);
484       FD_SET (icmpsock, &rs);
485       tv.tv_sec = 0;
486       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
487       if (0 != select (icmpsock + 1, &rs, NULL, NULL, &tv))
488         {
489           if (errno == EINTR)
490             continue;
491           fprintf (stderr,
492                    "select failed: %s\n",
493                    strerror (errno));
494           break;
495         }
496       if (FD_ISSET (icmpsock, &rs))
497         process_icmp_response ();
498       send_icmp_echo (&external);
499     }
500   closesocket(icmpsock);
501   closesocket(rawsock);
502   WSACleanup ();
503   return 4; /* select failed! */
504 }
505
506
507 /* end of gnunet-nat-server-windows.c */