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 uint16_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 /**
228  * Send an ICMP message to the target.
229  *
230  * @param my_ip source address
231  * @param other target address
232  */
233 static void
234 send_icmp_udp (const struct in_addr *my_ip,
235                const struct in_addr *other)
236 {
237   struct ip_packet ip_pkt;
238   struct icmp_packet icmp_pkt;
239   struct udp_packet udp_pkt;
240
241   struct sockaddr_in dst;
242   char packet[sizeof(ip_pkt) * 2 + sizeof(icmp_pkt) * 2 + sizeof(uint32_t)];
243
244   size_t off;
245   int err;
246
247   /* ip header: send to (known) ip address */
248   off = 0;
249   memset(&ip_pkt, 0, sizeof(ip_pkt));
250   ip_pkt.vers_ihl = 0x45;
251   ip_pkt.tos = 0;
252   ip_pkt.pkt_len = htons(sizeof (packet));
253   ip_pkt.id = htons(256);
254   ip_pkt.flags_frag_offset = 0;
255   ip_pkt.ttl = 128;
256   ip_pkt.proto = IPPROTO_ICMP;
257   ip_pkt.checksum = 0;
258   ip_pkt.src_ip = my_ip->s_addr;
259   ip_pkt.dst_ip = other->s_addr;
260   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
261   memcpy(&packet[off], &ip_pkt, sizeof(ip_pkt));
262   off += sizeof(ip_pkt);
263
264   /* ip header of the presumably 'lost' udp packet */
265   ip_pkt.vers_ihl = 0x45;
266   ip_pkt.tos = 0;
267   ip_pkt.pkt_len = (sizeof (struct ip_packet) + sizeof (struct icmp_echo_packet));
268
269   icmp_pkt.type = 11; /* TTL exceeded */
270   icmp_pkt.code = 0;
271   icmp_pkt.checksum = 0;
272   icmp_pkt.reserved = 0;
273   memcpy(&packet[off], &icmp_pkt, sizeof(icmp_pkt));
274   off += sizeof(icmp_pkt);
275
276   /* build inner IP header */
277   memset(&ip_pkt, 0, sizeof(ip_pkt));
278   ip_pkt.vers_ihl = 0x45;
279   ip_pkt.tos = 0;
280   ip_pkt.pkt_len = htons(sizeof (ip_pkt) + sizeof(udp_pkt));
281   ip_pkt.id = htons(0);
282   ip_pkt.flags_frag_offset = 0;
283   ip_pkt.ttl = 128;
284   ip_pkt.proto = IPPROTO_UDP;
285   ip_pkt.checksum = 0;
286   ip_pkt.src_ip = other->s_addr;
287   ip_pkt.dst_ip = dummy.s_addr;
288   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (ip_pkt)));
289   memcpy(&packet[off], &ip_pkt, sizeof(ip_pkt));
290   off += sizeof(ip_pkt);
291
292   /* build UDP header */
293   udp_pkt.src_port = htons(NAT_TRAV_PORT);
294   udp_pkt.dst_port = htons(NAT_TRAV_PORT);
295
296   memset(&udp_pkt.length, 0, sizeof(uint32_t));
297   udp_pkt.length = htons (port);
298   memcpy(&packet[off], &udp_pkt, sizeof(udp_pkt));
299   off += sizeof(udp_pkt);
300
301   /* set ICMP checksum */
302   icmp_pkt.checksum = htons(calc_checksum((uint16_t*)&packet[sizeof(ip_pkt)],
303                             sizeof (icmp_pkt) + sizeof(ip_pkt) + sizeof(udp_pkt)));
304   memcpy (&packet[sizeof(ip_pkt)], &icmp_pkt, sizeof (icmp_pkt));
305
306
307   memset (&dst, 0, sizeof (dst));
308   dst.sin_family = AF_INET;
309   dst.sin_addr = *other;
310   err = sendto(rawsock,
311                packet,
312                off, 0,
313                (struct sockaddr*)&dst,
314                sizeof(dst));
315
316   if (err < 0)
317     {
318       fprintf(stderr,
319               "sendto failed: %s\n", strerror(errno));
320     }
321   else if (err != off)
322     {
323       fprintf(stderr,
324               "Error: partial send of ICMP message\n");
325     }
326 }
327
328
329 /**
330  * Send an ICMP message to the target.
331  *
332  * @param my_ip source address
333  * @param other target address
334  */
335 static void
336 send_icmp (const struct in_addr *my_ip,
337            const struct in_addr *other)
338 {
339   struct ip_packet ip_pkt;
340   struct icmp_packet *icmp_pkt;
341   struct icmp_echo_packet icmp_echo;
342   struct sockaddr_in dst;
343   char packet[sizeof (struct ip_packet)*2 + sizeof (struct icmp_packet) + sizeof(struct icmp_echo_packet)];
344
345   size_t off;
346   int err;
347
348   memset(packet, 0, sizeof(packet));
349   /* ip header: send to (known) ip address */
350   off = 0;
351   memset(&ip_pkt, 0, sizeof(ip_pkt));
352   ip_pkt.vers_ihl = 0x45;
353   ip_pkt.tos = 0;
354   ip_pkt.pkt_len = sizeof (packet); /* huh? */
355   ip_pkt.id = 1; 
356   ip_pkt.flags_frag_offset = 0;
357   ip_pkt.ttl = IPDEFTTL;
358   ip_pkt.proto = IPPROTO_ICMP;
359   ip_pkt.checksum = 0; 
360   ip_pkt.src_ip = my_ip->s_addr;
361   ip_pkt.dst_ip = other->s_addr;
362   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (struct ip_packet)));
363
364   memcpy (packet, &ip_pkt, sizeof (struct ip_packet));
365   off += sizeof (ip_pkt);
366   memset (&dst, 0, sizeof (dst));
367   dst.sin_family = AF_INET;
368   dst.sin_addr = *other;
369
370   /* icmp reply: time exceeded */
371   icmp_pkt = (struct icmp_packet*) &packet[off];
372   memset(icmp_pkt, 0, sizeof(struct icmp_packet));
373   icmp_pkt->type = ICMP_TIME_EXCEEDED;
374   icmp_pkt->code = 0; 
375   icmp_pkt->reserved = 0;
376   icmp_pkt->checksum = 0;
377
378   off += sizeof (struct icmp_packet);
379
380   /* ip header of the presumably 'lost' udp packet */
381   ip_pkt.vers_ihl = 0x45;
382   ip_pkt.tos = 0;
383   ip_pkt.pkt_len = (sizeof (struct ip_packet) + sizeof (struct icmp_echo_packet));
384   ip_pkt.id = 1; 
385   ip_pkt.flags_frag_offset = 0;
386   ip_pkt.ttl = 1; /* real TTL would be 1 on a time exceeded packet */
387   ip_pkt.proto = IPPROTO_ICMP;
388   ip_pkt.src_ip = other->s_addr;
389   ip_pkt.dst_ip = dummy.s_addr;
390   ip_pkt.checksum = 0;
391   ip_pkt.checksum = htons(calc_checksum((uint16_t*)&ip_pkt, sizeof (struct ip_packet)));  
392   memcpy (&packet[off], &ip_pkt, sizeof (struct ip_packet));
393   off += sizeof (struct ip_packet);
394
395   icmp_echo.type = ICMP_ECHO;
396   icmp_echo.code = 0;
397   icmp_echo.reserved = 0;
398   icmp_echo.checksum = 0;
399   icmp_echo.data = htons(port);
400   icmp_echo.checksum = htons(calc_checksum((uint16_t*) &icmp_echo, 
401                                            sizeof (struct icmp_echo_packet)));
402
403   memcpy (&packet[off], &icmp_echo, sizeof(struct icmp_echo_packet));
404   off += sizeof (struct icmp_echo_packet);
405
406   icmp_pkt->checksum = htons(calc_checksum((uint16_t*)icmp_pkt,
407                                              sizeof (struct icmp_packet) + sizeof(struct ip_packet) + sizeof(struct icmp_echo_packet)));
408
409   err = sendto(rawsock, 
410                &packet[0],
411                off, 0,
412                (struct sockaddr*)&dst, 
413                sizeof(dst)); /* or sizeof 'struct sockaddr'? */
414
415   if (err < 0) 
416     {
417       fprintf(stderr,
418               "sendto failed: %s\n", strerror(errno));
419     }
420   else if (err != off) 
421     {
422       fprintf(stderr,
423               "Error: partial send of ICMP message\n");
424     }
425 }
426
427
428 /**
429  * Create an ICMP raw socket.
430  *
431  * @return INVALID_SOCKET on error
432  */
433 static SOCKET
434 make_raw_socket ()
435 {
436   DWORD bOptVal = TRUE;
437   int bOptLen = sizeof(bOptVal);
438   SOCKET ret;
439
440   ret = socket (AF_INET, SOCK_RAW, IPPROTO_RAW);
441   if (INVALID_SOCKET == ret)
442     {
443       fprintf (stderr,
444                "Error opening RAW socket: %s\n",
445                strerror (errno));
446       return INVALID_SOCKET;
447     }  
448   if (setsockopt(ret, SOL_SOCKET, SO_BROADCAST, (char*)&bOptVal, bOptLen) != 0)
449     {
450       fprintf(stderr, 
451               "Error setting SO_BROADCAST to ON: %s\n",
452               strerror (errno));
453       closesocket(rawsock);
454       return INVALID_SOCKET;
455     }
456
457   if (setsockopt(ret, IPPROTO_IP, IP_HDRINCL, (char*)&bOptVal, bOptLen) != 0)
458     {
459       fprintf(stderr, 
460               "Error setting IP_HDRINCL to ON: %s\n",
461               strerror (errno));
462       closesocket(rawsock);
463       return INVALID_SOCKET;
464     }
465   return ret;
466 }
467
468
469 int
470 main (int argc, char *const *argv)
471 {
472   struct in_addr external;
473   struct in_addr target;
474   WSADATA wsaData;
475
476   unsigned int p;
477
478   if (argc != 4)
479     {
480       fprintf (stderr,
481                "This program must be started with our IP, the targets external IP, and our port as arguments.\n");
482       return 1;
483     }
484   if ( (1 != inet_pton (AF_INET, argv[1], &external)) ||
485        (1 != inet_pton (AF_INET, argv[2], &target)) )
486     {
487       fprintf (stderr,
488                "Error parsing IPv4 address: %s\n",
489                strerror (errno));
490       return 1;
491     }
492   if ( (1 != sscanf (argv[3], "%u", &p) ) ||
493        (p == 0) ||
494        (p > 0xFFFF) )
495     {
496       fprintf (stderr,
497                "Error parsing port value `%s'\n",
498                argv[3]);
499       return 1;
500     }
501   port = (uint16_t) p;
502
503   if (WSAStartup (MAKEWORD (2, 1), &wsaData) != 0)
504     {
505       fprintf (stderr, "Failed to find Winsock 2.1 or better.\n");
506       return 2;
507     }
508   if (1 != inet_pton (AF_INET, DUMMY_IP, &dummy)) 
509     {
510       fprintf (stderr,
511                "Internal error converting dummy IP to binary.\n");
512       return 2;
513     }
514   if (-1 == (rawsock = make_raw_socket()))
515     return 3;
516   send_icmp (&external,
517              &target);
518   send_icmp_udp (&external,
519                  &target);
520   closesocket (rawsock);
521   WSACleanup ();
522   return 0;
523 }
524
525 /* end of gnunet-nat-client-windows.c */