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