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