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