2017d41be782e261b26b17071f7951da21308dcd
[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 0
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, void *buf)
149 {
150   int ret;
151   int ssize;
152
153   ssize = sizeof(buf);
154   ret = WSAStringToAddress (cp, af, NULL, (LPSOCKADDR)buf, &ssize);
155
156   if (ret == 0)
157     return 1;
158   else
159     return 0;
160 }
161 #endif
162
163 static void
164 make_echo (const struct in_addr *src_ip,
165            struct icmp_packet *echo)
166 {
167   memset(echo, 0, sizeof(struct icmp_packet));
168   echo->type = ICMP_ECHO;
169   echo->code = 0;
170   echo->reserved = 0;
171   echo->checksum = 0;
172   echo->checksum = htons(calc_checksum((uint16_t*)echo, sizeof (struct icmp_packet)));
173 }
174
175
176 /**
177  * Send an ICMP message to the dummy IP.
178  *
179  * @param my_ip source address (our ip address)
180  */
181 static void
182 send_icmp_echo (const struct in_addr *my_ip)
183 {
184   struct icmp_packet icmp_echo;
185   struct sockaddr_in dst;
186   size_t off;
187   int err;
188   struct ip_packet ip_pkt;
189   struct icmp_packet icmp_pkt;
190   char packet[sizeof (ip_pkt) + sizeof (icmp_pkt)];
191
192   off = 0;
193   memset(&ip_pkt, 0, sizeof(ip_pkt));
194   ip_pkt.vers_ihl = 0x45;
195   ip_pkt.tos = 0;
196   ip_pkt.pkt_len = sizeof (packet);
197   ip_pkt.id = 1;
198   ip_pkt.flags_frag_offset = 0;
199   ip_pkt.ttl = IPDEFTTL;
200   ip_pkt.proto = IPPROTO_ICMP;
201   ip_pkt.checksum = 0; 
202   ip_pkt.src_ip = my_ip->s_addr;
203   ip_pkt.dst_ip = dummy.s_addr;
204   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
205   memcpy (packet, &ip_pkt, sizeof (ip_pkt));
206   off += sizeof (ip_pkt);
207   make_echo (my_ip, &icmp_echo);
208   memcpy (&packet[off], &icmp_echo, sizeof (icmp_echo));
209   off += sizeof (icmp_echo);
210  
211   memset (&dst, 0, sizeof (dst));
212   dst.sin_family = AF_INET;
213   dst.sin_addr = dummy;
214   err = sendto(rawsock, 
215                packet, off, 0, 
216                (struct sockaddr*)&dst, 
217                sizeof(dst));
218   if (err < 0) 
219     {
220 #if VERBOSE
221       fprintf(stderr,
222               "sendto failed: %s\n", strerror(errno));
223 #endif
224     }
225   else if (err != off) 
226     {
227       fprintf(stderr,
228               "Error: partial send of ICMP message\n");
229     }
230 }
231
232
233 static void
234 process_icmp_response ()
235 {
236   char buf[65536];
237   ssize_t have;
238   struct in_addr sip;
239   struct ip_packet ip_pkt;
240   struct icmp_packet icmp_pkt;
241   struct udp_packet udp_pkt;
242   size_t off;
243   int have_port;
244   int have_udp;
245   uint32_t port;
246   char addr_buf[13];
247   have = read (icmpsock, buf, sizeof (buf));
248   if (have == -1)
249     {
250       fprintf (stderr,
251                "Error reading raw socket: %s\n",
252                strerror (errno));
253       return; 
254     }
255   have_port = 0;
256
257   if (have == sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2 + sizeof(uint32_t))
258     {
259       have_port = 1;
260     }
261   else if (have != sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2)
262     {
263 #if VERBOSE
264       fprintf (stderr,
265                "Received ICMP message of unexpected size: %u bytes\n",
266                (unsigned int) have);
267 #endif
268       return;
269     }
270   off = 0;
271   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
272   off += sizeof (ip_pkt);
273   memcpy (&icmp_pkt, &buf[off], sizeof (icmp_pkt));
274   off += sizeof (icmp_pkt);
275   if ( ((ip_pkt.proto != IPPROTO_ICMP) && (ip_pkt.proto != IPPROTO_UDP)) ||
276        (icmp_pkt.type != ICMP_TIME_EXCEEDED) || 
277        (icmp_pkt.code != 0) )
278     {
279       /* maybe we got an actual reply back... */
280       return;    
281     }
282   memcpy(&sip, 
283          &ip_pkt.src_ip, 
284          sizeof (sip));
285
286   memcpy (&ip_pkt, &buf[off], sizeof (ip_pkt));
287   off += sizeof (ip_pkt);
288
289   have_udp = 0;
290   if (ip_pkt.proto == IPPROTO_UDP)
291     {
292       have_udp = 1;
293     }
294
295   if (have_port)
296     {
297       memcpy(&port, &buf[sizeof (struct ip_packet) *2 + sizeof (struct icmp_packet) * 2], sizeof(uint32_t));
298       port = ntohs(port);
299 #ifdef WIN32
300       DWORD ssize = sizeof(buf);
301       WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
302       fprintf (stdout, "%s:%d\n", buf, port);
303 #else
304       fprintf (stdout,
305               "%s:%d\n",
306               inet_ntop (AF_INET,
307                          &sip,
308                          buf,
309                          sizeof (buf)), port);
310 #endif
311     }
312   else
313     {
314 #ifdef WIN32
315       DWORD ssize = sizeof(buf);
316       WSAAddressToString((LPSOCKADDR)&sip, sizeof(sip), NULL, buf, &ssize);
317       fprintf (stdout, "%s\n", buf);
318 #else
319       fprintf (stdout,
320               "%s\n",
321               inet_ntop (AF_INET,
322                          &sip,
323                          buf,
324                          sizeof (buf)));
325 #endif
326     }
327   fflush (stdout);
328 }
329
330
331 static Socket
332 make_icmp_socket ()
333 {
334   Socket ret;
335
336   ret = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
337   if (-1 == ret)
338     {
339       fprintf (stderr,
340                "Error opening RAW socket: %s\n",
341                strerror (errno));
342       return -1;
343     }  
344   if (ret >= FD_SETSIZE) 
345     {
346       fprintf (stderr,
347                "Socket number too large (%d > %u)\n",
348                ret,
349                (unsigned int) FD_SETSIZE);
350 #ifdef WIN32
351       closesocket (ret);
352 #else
353       close (ret);
354 #endif
355       return -1;
356     }
357   return ret;
358 }
359
360
361 static Socket
362 make_raw_socket ()
363 {
364   const int one = 1;
365   Socket ret;
366
367   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
368   if (-1 == ret)
369     {
370       fprintf (stderr,
371                "Error opening RAW socket: %s\n",
372                strerror (errno));
373       return -1;
374     }  
375   if (setsockopt(ret, SOL_SOCKET, SO_BROADCAST,
376                  (char *)&one, sizeof(one)) == -1)
377     fprintf(stderr,
378             "setsockopt failed: %s\n",
379             strerror (errno));
380   if (setsockopt(ret, IPPROTO_IP, IP_HDRINCL,
381                  (char *)&one, sizeof(one)) == -1)
382     fprintf(stderr,
383             "setsockopt failed: %s\n",
384             strerror (errno));
385   return ret;
386 }
387
388
389 int
390 main (int argc, char *const *argv)
391 {
392   struct in_addr external;
393   fd_set rs;
394   struct timeval tv;
395   uid_t uid;
396
397 #ifdef WIN32
398   // WSA startup
399   WSADATA wsaData;
400   if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
401   {
402       fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
403       return 4;                       // ERROR
404   }
405 #endif
406
407   if (-1 == (icmpsock = make_icmp_socket()))
408     return 1; 
409   if (-1 == (rawsock = make_raw_socket()))
410     {
411       close (icmpsock);
412       return 1; 
413     }
414 #ifndef WIN32
415   uid = getuid ();
416   if (0 != setresuid (uid, uid, uid))
417     fprintf (stderr,
418              "Failed to setresuid: %s\n",
419              strerror (errno));
420 #endif
421   if (argc != 2)
422     {
423       fprintf (stderr,
424                "This program must be started with our (internal NAT) IP as the only argument.\n");
425       return 1;
426     }
427
428   if (1 != inet_pton (AF_INET, argv[1], &external))
429     {
430       fprintf (stderr,
431                "Error parsing IPv4 address: %s\n",
432                strerror (errno));
433       return 1;
434     }
435
436   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) abort ();
437   while (1)
438     {
439       FD_ZERO (&rs);
440       FD_SET (icmpsock, &rs);
441       tv.tv_sec = 0;
442       tv.tv_usec = ICMP_SEND_FREQUENCY_MS * 1000; 
443       select (icmpsock + 1, &rs, NULL, NULL, &tv);
444       if (FD_ISSET (icmpsock, &rs))
445         process_icmp_response ();
446       send_icmp_echo (&external);
447     }  
448
449 #ifdef WIN32
450   closesocket(icmpsock);
451   closesocket(rawsock);
452   WSACleanup ();
453 #endif
454   return 0;
455 }
456
457
458 /* end of gnunet-nat-server-windows.c */