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