more code cleanup
[oweals/gnunet.git] / src / transport / gnunet-nat-client-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-client-windows.c
23  * @brief Tool to help bypass NATs using ICMP method; must run as
24  *        root (SUID will do) or administrator on W32
25  *        This code will work under GNU/Linux or W32.
26  * @author Nathan Evans
27  *
28  * This program will send ONE ICMP message using RAW sockets
29  * to the IP address specified as the second argument.  Since
30  * it uses RAW sockets, it must be installed SUID or run as 'root'.
31  * In order to keep the security risk of the resulting SUID binary
32  * minimal, the program ONLY opens the RAW socket with root
33  * privileges, then drops them and only then starts to process
34  * command line arguments.  The code also does not link against
35  * any shared libraries (except libc) and is strictly minimal
36  * (except for checking for errors).  The following list of people
37  * have reviewed this code and considered it safe since the last
38  * modification (if you reviewed it, please have your name added
39  * to the list):
40  *
41  * - Christian Grothoff
42  * - Nathan Evans
43  */
44 #define _GNU_SOURCE
45
46 #include <ws2tcpip.h>
47 #include <winsock2.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 #define ICMP_ECHO 8
60 #define IPDEFTTL 64
61 #define ICMP_TIME_EXCEEDED 11
62
63 /**
64  * Must match IP given in the server.
65  */
66 #define DUMMY_IP "192.0.2.86"
67
68 #define NAT_TRAV_PORT 22225
69
70 /**
71  * IPv4 header.
72  */
73 struct ip_packet 
74 {
75
76   /**
77    * Version (4 bits) + Internet header length (4 bits) 
78    */
79   uint8_t vers_ihl; 
80
81   /**
82    * Type of service
83    */
84   uint8_t tos;  
85
86   /**
87    * Total length
88    */
89   uint16_t pkt_len;  
90
91   /**
92    * Identification
93    */
94   uint16_t id;    
95
96   /**
97    * Flags (3 bits) + Fragment offset (13 bits)
98    */
99   uint16_t flags_frag_offset; 
100
101   /**
102    * Time to live
103    */
104   uint8_t  ttl;   
105
106   /**
107    * Protocol       
108    */
109   uint8_t  proto; 
110
111   /**
112    * Header checksum
113    */
114   uint16_t checksum; 
115
116   /**
117    * Source address
118    */
119   uint32_t  src_ip;  
120
121   /**
122    * Destination address 
123    */
124   uint32_t  dst_ip;  
125 };
126
127
128 /**
129  * Format of ICMP packet.
130  */
131 struct icmp_packet 
132 {
133   uint8_t type;
134
135   uint8_t code;
136
137   uint16_t checksum;
138
139   uint32_t reserved;
140 };
141
142 struct icmp_echo_packet
143 {
144   uint8_t type;
145   uint8_t code;
146   uint16_t checksum;
147   uint32_t reserved;
148   uint32_t data;
149 };
150
151 /**
152  * Beginning of UDP packet.
153  */
154 struct udp_packet
155 {
156   uint16_t src_port;
157
158   uint16_t dst_port;
159
160   uint32_t length;
161 };
162
163
164 /**
165  * Socket we use to send our ICMP packets.
166  */
167 static SOCKET rawsock;
168
169 /**
170  * Target "dummy" address.
171  */
172 static struct in_addr dummy;
173  
174 static uint32_t port;
175
176
177
178 /**
179  * Convert IPv4 address from text to binary form.
180  *
181  * @param af address family
182  * @param cp the address to print
183  * @param buf where to write the address result
184  * @return 1 on success
185  */
186 static int 
187 inet_pton (int af, 
188            const char *cp, 
189            struct in_addr *buf)
190 {
191   buf->s_addr = inet_addr(cp);
192   if (buf->s_addr == INADDR_NONE)
193     {
194       fprintf(stderr, 
195               "Error %d handling address %s", 
196               WSAGetLastError(), 
197               cp);
198       return 0;
199     }
200   return 1;
201 }
202
203
204 /**
205  * CRC-16 for IP/ICMP headers.
206  *
207  * @param data what to calculate the CRC over
208  * @param bytes number of bytes in data (must be multiple of 2)
209  * @return the CRC 16.
210  */
211 static uint16_t 
212 calc_checksum(const uint16_t *data, 
213               unsigned int bytes)
214 {
215   uint32_t sum;
216   unsigned int i;
217
218   sum = 0;
219   for (i=0;i<bytes/2;i++) 
220     sum += data[i];        
221   sum = (sum & 0xffff) + (sum >> 16);
222   sum = htons(0xffff - sum);
223   return sum;
224 }
225
226
227 static void
228 make_echo (const struct in_addr *src_ip,
229            struct icmp_echo_packet *echo, uint32_t num)
230 {
231   memset(echo, 0, sizeof(struct icmp_echo_packet));
232   echo->type = ICMP_ECHO;
233   echo->code = 0;
234   echo->reserved = 0;
235   echo->checksum = 0;
236   echo->data = htons(num);
237   echo->checksum = htons(calc_checksum((uint16_t*)echo, 
238                                        sizeof (struct icmp_echo_packet)));
239 }
240
241 /**
242  * Send an ICMP message to the target.
243  *
244  * @param my_ip source address
245  * @param other target address
246  */
247 static void
248 send_icmp_udp (const struct in_addr *my_ip,
249                const struct in_addr *other)
250 {
251   struct ip_packet ip_pkt;
252   struct icmp_packet icmp_pkt;
253   struct udp_packet udp_pkt;
254
255   struct sockaddr_in dst;
256   char packet[sizeof(ip_pkt) * 2 + sizeof(icmp_pkt) * 2 + sizeof(uint32_t)];
257
258   size_t off;
259   int err;
260
261   /* ip header: send to (known) ip address */
262   off = 0;
263   memset(&ip_pkt, 0, sizeof(ip_pkt));
264   ip_pkt.vers_ihl = 0x45;
265   ip_pkt.tos = 0;
266   ip_pkt.pkt_len = htons(sizeof (packet));
267   ip_pkt.id = htons(256);
268   ip_pkt.flags_frag_offset = 0;
269   ip_pkt.ttl = 128;
270   ip_pkt.proto = IPPROTO_ICMP;
271   ip_pkt.checksum = 0;
272   ip_pkt.src_ip = my_ip->s_addr;
273   ip_pkt.dst_ip = other->s_addr;
274   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
275   memcpy(&packet[off], &ip_pkt, sizeof(ip_pkt));
276   off += sizeof(ip_pkt);
277
278   /* ip header of the presumably 'lost' udp packet */
279   ip_pkt.vers_ihl = 0x45;
280   ip_pkt.tos = 0;
281   ip_pkt.pkt_len = (sizeof (struct ip_packet) + sizeof (struct icmp_echo_packet));
282
283   icmp_pkt.type = 11; /* TTL exceeded */
284   icmp_pkt.code = 0;
285   icmp_pkt.checksum = 0;
286   icmp_pkt.reserved = 0;
287   memcpy(&packet[off], &icmp_pkt, sizeof(icmp_pkt));
288   off += sizeof(icmp_pkt);
289
290   /* build inner IP header */
291   memset(&ip_pkt, 0, sizeof(ip_pkt));
292   ip_pkt.vers_ihl = 0x45;
293   ip_pkt.tos = 0;
294   ip_pkt.pkt_len = htons(sizeof (ip_pkt) + sizeof(udp_pkt));
295   ip_pkt.id = htons(0);
296   ip_pkt.flags_frag_offset = 0;
297   ip_pkt.ttl = 128;
298   ip_pkt.proto = IPPROTO_UDP;
299   ip_pkt.checksum = 0;
300   ip_pkt.src_ip = other->s_addr;
301   ip_pkt.dst_ip = dummy.s_addr;
302   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
303   memcpy(&packet[off], &ip_pkt, sizeof(ip_pkt));
304   off += sizeof(ip_pkt);
305
306   /* build UDP header */
307   udp_pkt.src_port = htons(NAT_TRAV_PORT); /* FIXME: does this port matter? */
308   udp_pkt.dst_port = htons(NAT_TRAV_PORT);
309
310   memset(&udp_pkt.length, 0, sizeof(uint32_t));
311   udp_pkt.length = htonl(port);
312   memcpy(&packet[off], &udp_pkt, sizeof(udp_pkt));
313   off += sizeof(udp_pkt);
314
315   /* set ICMP checksum */
316   icmp_pkt.checksum = htons(calc_checksum((uint16_t*)&packet[sizeof(ip_pkt)],
317                             sizeof (icmp_pkt) + sizeof(ip_pkt) + sizeof(udp_pkt)));
318   memcpy (&packet[sizeof(ip_pkt)], &icmp_pkt, sizeof (icmp_pkt));
319
320
321   memset (&dst, 0, sizeof (dst));
322   dst.sin_family = AF_INET;
323   dst.sin_addr = *other;
324   err = sendto(rawsock,
325                packet,
326                off, 0,
327                (struct sockaddr*)&dst,
328                sizeof(dst));
329
330   if (err < 0)
331     {
332       fprintf(stderr,
333               "sendto failed: %s\n", strerror(errno));
334     }
335   else if (err != off)
336     {
337       fprintf(stderr,
338               "Error: partial send of ICMP message\n");
339     }
340 }
341
342
343 /**
344  * Send an ICMP message to the target.
345  *
346  * @param my_ip source address
347  * @param other target address
348  */
349 static void
350 send_icmp (const struct in_addr *my_ip,
351            const struct in_addr *other)
352 {
353   struct ip_packet ip_pkt;
354   struct icmp_packet *icmp_pkt;
355   struct icmp_echo_packet icmp_echo;
356   struct sockaddr_in dst;
357   char packet[sizeof (struct ip_packet)*2 + sizeof (struct icmp_packet) + sizeof(struct icmp_echo_packet)];
358
359   size_t off;
360   int err;
361
362   memset(packet, 0, sizeof(packet));
363   /* ip header: send to (known) ip address */
364   off = 0;
365   memset(&ip_pkt, 0, sizeof(ip_pkt));
366   ip_pkt.vers_ihl = 0x45;
367   ip_pkt.tos = 0;
368   ip_pkt.pkt_len = sizeof (packet); /* huh? */
369   ip_pkt.id = 1; 
370   ip_pkt.flags_frag_offset = 0;
371   ip_pkt.ttl = IPDEFTTL;
372   ip_pkt.proto = IPPROTO_ICMP;
373   ip_pkt.checksum = 0; 
374   ip_pkt.src_ip = my_ip->s_addr;
375   ip_pkt.dst_ip = other->s_addr;
376   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (struct ip_packet)));
377
378   memcpy (packet, &ip_pkt, sizeof (struct ip_packet));
379   off += sizeof (ip_pkt);
380   memset (&dst, 0, sizeof (dst));
381   dst.sin_family = AF_INET;
382   dst.sin_addr = *other;
383
384   /* icmp reply: time exceeded */
385   icmp_pkt = (struct icmp_packet*) &packet[off];
386   memset(icmp_pkt, 0, sizeof(struct icmp_packet));
387   icmp_pkt->type = ICMP_TIME_EXCEEDED;
388   icmp_pkt->code = 0; 
389   icmp_pkt->reserved = 0;
390   icmp_pkt->checksum = 0;
391
392   off += sizeof (struct icmp_packet);
393
394   /* ip header of the presumably 'lost' udp packet */
395   ip_pkt.vers_ihl = 0x45;
396   ip_pkt.tos = 0;
397   ip_pkt.pkt_len = (sizeof (struct ip_packet) + sizeof (struct icmp_echo_packet));
398   ip_pkt.id = 1; 
399   ip_pkt.flags_frag_offset = 0;
400   ip_pkt.ttl = 1; /* real TTL would be 1 on a time exceeded packet */
401   ip_pkt.proto = IPPROTO_ICMP;
402   ip_pkt.src_ip = other->s_addr;
403   ip_pkt.dst_ip = dummy.s_addr;
404   ip_pkt.checksum = 0;
405   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (struct ip_packet)));  
406   memcpy (&packet[off], &ip_pkt, sizeof (struct ip_packet));
407   off += sizeof (struct ip_packet);
408
409   make_echo (other, &icmp_echo, port);
410   memcpy (&packet[off], &icmp_echo, sizeof(struct icmp_echo_packet));
411   off += sizeof (struct icmp_echo_packet);
412
413   icmp_pkt->checksum = htons(calc_checksum((uint16_t*)icmp_pkt,
414                                              sizeof (struct icmp_packet) + sizeof(struct ip_packet) + sizeof(struct icmp_echo_packet)));
415
416   err = sendto(rawsock, 
417                &packet[0],
418                off, 0,
419                (struct sockaddr*)&dst, 
420                sizeof(dst)); /* or sizeof 'struct sockaddr'? */
421
422   if (err < 0) 
423     {
424       fprintf(stderr,
425               "sendto failed: %s\n", strerror(errno));
426     }
427   else if (err != off) 
428     {
429       fprintf(stderr,
430               "Error: partial send of ICMP message\n");
431     }
432 }
433
434
435 /**
436  * Create an ICMP raw socket.
437  *
438  * @return INVALID_SOCKET on error
439  */
440 static SOCKET
441 make_raw_socket ()
442 {
443   DWORD bOptVal = TRUE;
444   int bOptLen = sizeof(bOptVal);
445   SOCKET ret;
446
447   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
448   if (INVALID_SOCKET == ret)
449     {
450       fprintf (stderr,
451                "Error opening RAW socket: %s\n",
452                strerror (errno));
453       return INVALID_SOCKET;
454     }  
455   if (setsockopt(ret, SOL_SOCKET, SO_BROADCAST, (char*)&bOptVal, bOptLen) != 0)
456     {
457       fprintf(stderr, 
458               "Error setting SO_BROADCAST to ON: %s\n",
459               strerror (errno));
460       closesocket(rawsock);
461       return INVALID_SOCKET;
462     }
463
464   if (setsockopt(ret, IPPROTO_IP, IP_HDRINCL, (char*)&bOptVal, bOptLen) != 0)
465     {
466       fprintf(stderr, 
467               "Error setting IP_HDRINCL to ON: %s\n",
468               strerror (errno));
469       closesocket(rawsock);
470       return INVALID_SOCKET;
471     }
472   return ret;
473 }
474
475
476 int
477 main (int argc, char *const *argv)
478 {
479   struct in_addr external;
480   struct in_addr target;
481   WSADATA wsaData;
482
483   unsigned int p;
484
485   if (argc != 4)
486     {
487       fprintf (stderr,
488                "This program must be started with our IP, the targets external IP, and our port as arguments.\n");
489       return 1;
490     }
491   if ( (1 != inet_pton (AF_INET, argv[1], &external)) ||
492        (1 != inet_pton (AF_INET, argv[2], &target)) )
493     {
494       fprintf (stderr,
495                "Error parsing IPv4 address: %s\n",
496                strerror (errno));
497       return 1;
498     }
499   if ( (1 != sscanf (argv[3], "%u", &p) ) ||
500        (p == 0) ||
501        (p > 0xFFFF) )
502     {
503       fprintf (stderr,
504                "Error parsing port value `%s'\n",
505                argv[3]);
506       return 1;
507     }
508   port = (uint16_t) p;
509
510   if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
511     {
512       fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
513       return 2;
514     }
515   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) 
516     {
517       fprintf (stderr,
518                "Internal error converting dummy IP to binary.\n");
519       return 2;
520     }
521   if (-1 == (rawsock = make_raw_socket()))
522     return 3;
523   send_icmp (&external,
524              &target);
525   send_icmp_udp (&external,
526                  &target);
527   closesocket (rawsock);
528   WSACleanup ();
529   return 0;
530 }
531
532 /* end of gnunet-nat-client-windows.c */